reprogrammer
reprogrammer

Reputation: 14718

How can I fit a tall bar in a barplot?

The following R script generates a bar that is too tall to fit in the plot. Note that the bar goes beyond the y axis and its annotation (percentage) is not shown. How can I generate a bar plot that shows the whole tall bar and its annotation?

png(filename = "plot.png")
x <- c("A", "B")
y <- c(2e6 + 10, 400)
sum_Y <- sum(y)
midpoints <- barplot(height = y, log = "y")
text(midpoints, y, sprintf("%.2f%%", y / sum_Y * 100), pos = 3)
dev.off()

a bar plot with a tall bar

Upvotes: 2

Views: 612

Answers (3)

Geek On Acid
Geek On Acid

Reputation: 6410

Another option (based on @Dwin ylab adjustment) is to use plotrix package. If you want to play more with the log scale labels, check height.at and height.lab option in barp:

require(plotrix)
png(filename = "plot.png")
x <- c("A", "B")
y <- c(2e6 + 10, 400)
sum_Y <- sum(y)
midpoints <- barp(height = y, ylog = T, ylim=c(1,5e6))
text(y, sprintf("%.2f%%", y / sum_Y * 100), pos = 3)
dev.off()

enter image description here

Upvotes: 1

IRTFM
IRTFM

Reputation: 263311

png(filename = "plot.png")
x <- c("A", "B")
y <- c(2e6 + 10, 400)
sum_Y <- sum(y)
midpoints <- barplot(height = y, log = "y", ylim=c(5e1,5e6))
text(midpoints, y, sprintf("%.2f%%", y / sum_Y * 100), pos = 3)
dev.off()

R is rather picky about what it will accept as limits for its log scales.

enter image description here

Upvotes: 5

James
James

Reputation: 66834

You could do it in ggplot2:

library(ggplot2)
qplot(x,y,geom="bar",log="y") + geom_text(aes(y=y*1.5, label=sprintf("%.2f%%", y / sum_Y * 100)))

enter image description here

Upvotes: 1

Related Questions