我有以下数据
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
Run Code Online (Sandbox Code Playgroud)
我想从这些数据创建一个分组条形图,使得x轴包含Input字段(作为组),y轴表示Rtime和Btime字段(两个条形)的对数比例.
我在网上查看的所有解决方案/示例都将类似数据放入三列布局中.我不知道如何使用我生成分组条形图的数据.或者,如果有一种方法可以将这些数据(手动转换不是一个选项,因为它是一个包含大量行的大文件)转换为R和ggplot兼容的数据格式.
编辑:
使用gncs解决方案生成的图表

jor*_*ran 25
根据要求,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()
Run Code Online (Sandbox Code Playgroud)

注意风格区别就在这里,因为在那里log(1) = 0,GGPLOT2把它伪装成零高度的酒吧,不绘制任何东西,而barplot情节有点存根(这在我看来是有点误导).
根据要求,ggplot2解决方案还使用pivot_longer() https://tidyr.tidyverse.org/reference/pivot_longer.htmlgeom_bar()将数据转换为可以轻松绘制的格式geom_col()。position = "dodge"意味着制作多列样式(不是堆叠栏)。 geom_bar(stat = "identity")是相同的geom_col()。
使用更清晰的代码更新:
library(tidyverse)
df %>%
pivot_longer(-Input) %>%
ggplot(aes(x = Input, y = value, fill = name)) +
geom_col(position = "dodge") +
# geom_bar(stat = "identity", position = "dodge") +
scale_y_log10()
Run Code Online (Sandbox Code Playgroud)
原答案:
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, fill = variable)) +
geom_bar(stat = "identity", position = "dodge") +
scale_y_log10()
Run Code Online (Sandbox Code Playgroud)
小智 6
我想我理解这个问题,这就是我的建议(短期 - 选项):
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)
Run Code Online (Sandbox Code Playgroud)
那是你要的吗?它有点脏,但它可以完成这项工作.
更新:代码已更正.