简体   繁体   中英

Create labels in a side-by-side bar chart with coord flip in ggplot

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,

这实际上是我想要创建的,

Try using geom_text :

library(ggplot2)

ggplot(df, aes(x = x, y = z, fill = y, label = z)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(width= 1), vjust= 1.5, hjust = -0.5) + 
  coord_flip()

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM