【问题标题】:Draw bars in bar chart next to each other instead of vertically stacked在条形图中绘制的条形彼此相邻而不是垂直堆叠
【发布时间】:2023-02-04 23:47:41
【问题描述】:

我被 R 脚本困了一个星期 我正在尝试制作图表,但我无法为我的数据获得单独的条形图,它们相互叠加

我有一个包含 3 列的 excel 文件, column1:表示为序列的 X 的值(T、U、K、L ....等) Column2:第一批数据对应Y轴的百分比值 Column3:Y轴对应的第二批数据的百分比值

我想用棍子画一个图形,每批都有一种颜色,每批的棍子并排

excel表格示例:

COG_category      involved_percent      BO4_percent
NC                  22.01                   20.47
S                   17.25                   18.95
T                   14.96                   7.83
Y                   8.8                     7.17

data <- structure(list(COG_category = c("NC", "S", "T", "Y"), involved_percent = c(22.01, 
17.25, 14.96, 8.8), BO4_percent = c(20.47, 18.95, 7.83, 7.17)), class = "data.frame", row.names = c(NA, 
-4L))

我的 R 脚本:

#read file
data<- read.csv2("COGs_graph.csv")
data
library(ggplot2)
 
#Plot the data
ggplot(data, aes(x = COG_category, y = involved_percent, fill = "involved_percent")) +
 geom_col(width = 0.5, position = "dodge") +
 geom_col(aes(x = COG_category, y = BO4_percent, fill = "BO4_percent"), width = 0.5, position = "dodge") +
 scale_fill_manual(name = "Legend", values = c("Candidate_percent" = "blue", "BO4_percent" = "red")) +
 xlab("Value of X") + ylab("Percentage") +
 ggtitle("Figure title") +
 theme(legend. position = "bottom")

我获得的结果的图像:

我想执行这样的图像:

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    下面是它的工作原理。以长格式输入数据(使用 ggplot 时总是一个好主意),删除 ggplot 中的第二个 geom_col,调整名称:

    library(tidyverse)
    data %>% 
      pivot_longer(-COG_category) %>% 
      ggplot(aes(x = COG_category, y = value, fill = name)) + 
      geom_col(width = 0.5, position = "dodge") +
      scale_fill_manual(name = "Legend", values = c("involved_percent" = "blue", "BO4_percent" = "red")) + 
      xlab("Value of X") + ylab("Percentage") + 
      ggtitle("Figure title") + 
      theme(legend.position = "bottom")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多