如果以前曾经问过这个问题,请道歉,但很难明确表达以便找到答案。
我在下面有以下数据集。在R中,我想为PV1和……构建一个条形图。
您需要使用以下内容重新整形数据 melt() 和 dcast() 功能来自 reshape2 :
melt()
dcast()
reshape2
library(reshape2) library(ggplot2) df <- data.frame( row.names = c("PV1", "PV2"), AvgRead = c(20, 40), MinRead = c(10, 20), MaxRead = c(40, 80), AvgUniq = c(40, 80), MinUniq = c(20, 40), MaxUniq = c(70, 160) ) df$name <- row.names(df) df_molten <- melt(df) df_molten$var1 <- substr(df_molten$variable, 1, 3) df_molten$var2 <- substr(df_molten$variable, 4, 10000) df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value") ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) + geom_bar(stat = "identity", position = "dodge") + geom_errorbar( aes(ymin = Min, ymax = Max), width = 0.5, size = 1.3, position = position_dodge(0.9) )
的 编辑: 强> 要更改条形图的顺序,需要将var2更改为因子并相应地对级别进行排序:
df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value") df_cast$var2 <- factor(df_cast$var2, levels = c("Uniq", "Read")) ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) + geom_bar(stat = "identity", position = "dodge") + geom_errorbar( aes(ymin = Min, ymax = Max), width = 0.5, size = 1.3, position = position_dodge(0.9) )