I am trying to create labels for a side-by-side bar chart in R. I have flipped the coordinates. Here is an example,
x <- c("USA", "Canada", "Pakistan", "USA", "Canada", "Pakistan")
y <- c("FY18", "FY18", "FY18", "FY19", "FY19", "FY19")
z <- c(8, 9, 4, 3, 4, 10)
df <- data.frame(x, y, z)
p1 <- ggplot(df, aes(x = x, y = z, fill = y)) +
geom_bar(stat = "identity", position = "dodge") +
coord_flip()
p1
p2 <- p1 + annotate("text", x = df$x,
y = max(df$z) + 5,
label = df$z,
col = "black")
p2
Here is what the graph looks like:
I want the labels on the right side. But the labels are overlapping. I have tried multiple times to fix this but nothing seems to work. I have also tried to place labels on the bars but the positioning is off.
Here is actually what I am trying to create,
I figured out the answer,
library(ggplot2)
df <- data.frame(
stringsAsFactors = FALSE,
x = c("USA", "Canada", "Pakistan", "USA", "Canada", "Pakistan"),
y = c("FY18", "FY18", "FY18", "FY19", "FY19", "FY19"),
z = c(8, 9, 4, 3, 4, 10)
)
ggplot(df, aes(y = x, x = z, fill = y)) +
geom_col(position = "dodge") +
geom_text(aes(x = max(z) + 5, label = z),
position = position_dodge(width = 1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.