[英]Creating grouped bar-plot of multi-column data in R
我有以下数据
Input Rtime Rcost Rsolutions Btime Bcost
1 12 proc. 1 36 614425 40 36
2 15 proc. 1 51 534037 50 51
3 18-proc 5 62 1843820 66 66
4 20-proc 4 68 1645581 104400 73
5 20-proc(l) 4 64 1658509 14400 65
6 21-proc 10 78 3923623 453600 82
我想根据这些数据创建一个分组条形图,这样 x 轴包含Input
字段(作为组),y 轴代表 Rtime 和 Btime 字段(两个条形)的对数刻度。
我在线查看的所有解决方案/示例都将类似的数据放入三列布局中。 我不知道如何使用我必须生成分组条形图的数据。 或者,如果有办法将这些数据(手动转换不是一种选择,因为它是一个包含很多行的巨大文件)转换为R和ggplot兼容的数据格式。
编辑 :
使用 gncs 解决方案生成的图形
根据要求,一个ggplot2解决方案也使用reshape2 :
library(reshape2)
df <- read.table(text = " Input Rtime Rcost Rsolutions Btime Bcost
1 12-proc. 1 36 614425 40 36
2 15-proc. 1 51 534037 50 51
3 18-proc 5 62 1843820 66 66
4 20-proc 4 68 1645581 104400 73
5 20-proc(l) 4 64 1658509 14400 65
6 21-proc 10 78 3923623 453600 82",header = TRUE,sep = "")
dfm <- melt(df[,c('Input','Rtime','Btime')],id.vars = 1)
ggplot(dfm,aes(x = Input,y = value)) +
geom_bar(aes(fill = variable),stat = "identity",position = "dodge") +
scale_y_log10()
请注意此处的样式差异,因为log(1) = 0
, ggplot2将其视为零高度的条并且不绘制任何内容,而barplot
绘制了一个小存根(在我看来这有点误导)。
我想我理解这个问题,这就是我的建议(短期 - 选项):
data <- read.table("data.txt", header=TRUE)
subset <- t(data.frame(data$Rtime, data$Btime))
barplot(subset, legend = c("Rtime", "Btime"), names.arg=data$Input, log="y", beside=TRUE)
那是你要的吗? 它有点脏,但它可以完成工作。
更新:代码更正。
根据要求, ggplot2
解决方案也使用pivot_longer()
https://tidyr.tidyverse.org/reference/pivot_longer.html将数据转换为geom_bar()
可以轻松绘制的格式。
library(dplyr)
library(ggplot2)
df <- read.table(text = " Input Rtime Rcost Rsolutions Btime Bcost
1 12-proc. 1 36 614425 40 36
2 15-proc. 1 51 534037 50 51
3 18-proc 5 62 1843820 66 66
4 20-proc 4 68 1645581 104400 73
5 20-proc(l) 4 64 1658509 14400 65
6 21-proc 10 78 3923623 453600 82",
header = TRUE,sep = "")
dfm <- pivot_longer(df, -Input, names_to="variable", values_to="value")
## pivot_longer takes the input data frame, excludes the Input field from the transformation, turns the remaining column names into the variable "variable" (often called the "key"), and assigns the values to the variable "value".
ggplot(dfm,aes(x = Input,y = value)) +
geom_bar(aes(fill = variable),stat = "identity",position = "dodge") +
scale_y_log10()
joran 的回答对我帮助很大,但我不得不在 ggplot 语句中使用stat="identity" ,如下所示:
ggplot(dfm, aes(x = Input,y = value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity") +
scale_y_log10()
我的 R 版本是 3.2.2 和 ggplot2 版本 1.0.1
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.