【问题标题】:Drawing a barchart to compare two sets of data using ggplot2 package?使用 ggplot2 包绘制条形图以比较两组数据?
【发布时间】:2014-01-25 10:25:23
【问题描述】:

构建条形图以比较两组数据的最佳方法是什么?

例如数据集:

Number <- c(1,2,3,4)
Yresult <- c(1233,223,2223,4455)
Xresult <- c(1223,334,4421,0)
nyx <- data.frame(Number, Yresult, Xresult)

我想要的是 X 上的数字和彼此并排的代表各个 X 和 Y 值的条形

【问题讨论】:

  • 这样的问题太多了-标准程序:将(从reshape2)数据帧熔化为长格式,然后您可以设置aes(x = number,y = value,fill = variable) where variable将指示 yresult 或 xresult
  • 好吧,阅读文档或查看其中一个教程。但是,有些人认为“出版质量数据”和条形图是相互排斥的。
  • an online reference for the ggplot2 包。 Winston ChangR Graphics Cookbook 一书也是一个很好的资源。
  • 我很同情你的问题。 ggplot 太棒了。文档,不多。如果您是新手,这真的很令人困惑。试试this link
  • 顺便说一句:请参阅this link,了解有关如何提出更有可能得到答复的问题的建议。

标签: r ggplot2 bar-chart


【解决方案1】:

最好将数据重新整形为长格式。例如,您可以使用 reshape2 包的 melt 函数来做到这一点(替代方案是来自 base R 的 reshape,来自 data.tablemelt(即reshape2) 的 melt 函数和 tidyrgather 的扩展实现。

使用您的数据集:

# load needed libraries
library(reshape2)
library(ggplot2)

# reshape your data into long format
nyxlong <- melt(nyx, id=c("Number"))

# make the plot
ggplot(nyxlong) +
  geom_bar(aes(x = Number, y = value, fill = variable), 
           stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Result\n", values = c("red","blue"), 
                    labels = c(" Yresult", " Xresult")) +
  labs(x="\nNumber",y="Result\n") +
  theme_bw(base_size = 14)

给出以下条形图:

【讨论】:

  • 谢谢!这为我提供了我正在寻找的 ggplot2 的初始起点。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-09-27
  • 2014-01-17
  • 1970-01-01
  • 2013-06-08
  • 2013-04-08
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多