【问题标题】:How do I plot more than one series using qplot?如何使用 qplot 绘制多个系列?
【发布时间】:2011-02-26 08:34:56
【问题描述】:

我正在尝试使用以下数据了解如何在一个情节上拥有多个系列。

Year <- c('1950', '1960', '1970', '1980')
Bus <- c(10,20,30,40)
Bus.sd <- c(1.1, 2.2, 3.3, 4.4)
Car <- c(20, 20, 40, 40)
Car.sd <- c(1.1, 2.2, 3.3, 4.4)

sample_data = data.frame(Year, Bus, Bus.sd, Car, Car.sd)

qplot(Year, Bus, data=sample_data, geom="pointrange", 
ymin = Bus - Bus.sd/2, ymax = Bus + Bus.sd/2)

例如,使用上面的数据,我如何在同一个图上以不同的颜色显示 sample_data$Bus 和 sample_data$Car?

我尝试做的是:

p <- qplot(...)

然后

p <- p + qplot(...) 

我复制了上一行,但这给了我一个错误。

我不完全了解 AES 的工作原理。我研究了 ggplot2 示例,但很难理解这里的相关示例。或者,如果可以使用这些数据制作一个堆叠条(geom_bar),我认为这也可以适当地表示它。

【问题讨论】:

  • 你能重现graphs包中的图吗?或者以某种方式绘制它......

标签: r ggplot2


【解决方案1】:

希望对你有帮助

gplot2 最适合长格式的数据,如下所示:

  Year score  sd variable
1 1950    10 1.1      bus
2 1960    20 2.2      bus
3 1970    30 3.3      bus
4 1980    40 4.4      bus
5 1950    20 1.1      car
6 1960    20 2.2      car
7 1970    40 3.3      car
8 1980    40 4.4      car

这会将数据导入 R:

data <- structure(list(Year = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L), class = "factor", .Label = c("1950", "1960", "1970", "1980"
)), score = c(10, 20, 30, 40, 20, 20, 40, 40), sd = c(1.1, 2.2, 
3.3, 4.4, 1.1, 2.2, 3.3, 4.4), variable = c("bus", "bus", "bus", 
"bus", "car", "car", "car", "car")), .Names = c("Year", "score", 
"sd", "variable"), row.names = c(NA, -8L), class = "data.frame")

这将使情节,躲避一切。你需要躲闪,因为你的数据是重叠的。您可以通过“W”值控制闪避量。

ggplot(data, aes(x=Year, y=score,col=variable))+
geom_point(position=position_dodge(w=0.2))+
geom_pointrange(aes(ymin=score-sd, ymax=score+sd,group=Year),position=position_dodge(w=0.2))

【讨论】:

  • 参见。 “数据”示例。 “公共汽车”和“汽车”不是两个不同的变量 - 而是相同“想象”变量的两个类别,例如“车辆”。 sd 和 score 也是如此。
  • Hadleys melt 和 cast 包非常擅长将数据集转换为不同的形式。
  • 哦,我明白了。谢谢。我认为这就是为什么我很难理解 AES 部分。我不明白你是如何构建数据框的;我会看看熔化和铸造。
  • 我手动制作了数据框。我的融化和施法技能有些有限,所以在这个例子中更容易。如果你得到这种格式的数据,那么可能会问另一个关于如何融化的 SO 问题。
  • 因为你有重叠的点,你也应该看看 position_dodge。
猜你喜欢
  • 1970-01-01
  • 2021-04-21
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多