如何创建包含 y 的多列数据的 ggplot 条形图?

How to create a ggplot bar chart with multiple columns of data for y?

我的数据集如下所示:

这是一个 table 数据样本: |城市 |平均客户端使用率 | AverageClientEst |预估流量 | |--------|--------------------|---------------- |--------------------| |亚特兰大 |2695.68 |3555.62 |2812.89 | |波士顿 |559.48 |1080.49 |583.81 | |芝加哥 |3314.44 |5728 |3458.56 |

我希望 ggplot 使用城市作为 X 轴,并为 x 轴上的每个点设置三个条,一个用于 AverageClientUsage,一个用于 AverageClientEst,一个用于 EstimatedTraffic。我该怎么做呢?最后我希望 ggplot 看起来像这样:

首先,您需要pivot_longer()您的数据框:

library(dplyr)
df_long <- df %>% pivot_longer(!City, names_to = "Type", values_to = "Count")

之后,您可以在 geom_col()

中创建按类型填充的柱形图和 using position = "dodge"
library(ggplot)
ggplot(df_long, aes(x = City, y = Count, fill = Type)) + # specify x and y axis, specify fill
         geom_col(position = position_dodge(0.7), width = 0.6, color = "black") + # position.dodge sets the bars side by side
  theme_minimal() + # add a ggplot theme
  theme(legend.position = "bottom", # move legend to bottom
        legend.title = element_blank(), # remove legend title
        axis.text.x = element_text(angle = 45, vjust = 0.5, color = "gray33"), # rotate x axis text by 45 degrees, center again, change color
        axis.text.y = element_text(color = "gray33"), # change y axis text coor
        axis.title = element_blank(), # remove axis titles
        panel.grid.major.x = element_blank()) + # remove vertical grid lines
  scale_fill_manual(values = c("blue", "darkorange2", "gray")) # adjust the bar colors

数据

df <- structure(list(City = c("Atlanta", "Boston", "Chicago"), AverageClientUsage = c(2695.68, 
      559.48, 3314.44), AverageClientEst = c(3555.62, 1080.49, 5728
      ), EstimatedTraffic = c(2812.89, 583.81, 3458.56)), class = c("tbl_df", 
      "tbl", "data.frame"), row.names = c(NA, -3L))