r - 在ggplot2中绘制每个第二个数据点

标签 r ggplot2

我有以下数据集:

Data <- data.frame(
    week = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
    variable = c("nuclear", "nuclear", "nuclear", "nuclear", "atomic", "atomic", "atomic", "atomic", "unemployment", "unemployment", "unemployment", "unemployment"),
    value = c(2, 3, 1, 4, 5, 1, 2, 3, 3, 2, 5, 1)
)

我需要一个黑白图。所以我使用以下代码:

ggplot(Data, aes(week, value, group=variable)) + xlab("Year") + ylab("Frequency of searches") +
  geom_line(aes(linetype=variable))+ # Line type depends on cond
  geom_point(aes(shape=variable))+  # Shape depends on cond
  scale_shape_manual(values=c(0,1,2)) + # Change shapes
  scale_linetype_manual(values=c("solid", "dotted", "dotdash"))+
  theme(legend.position="top", legend.title=element_blank(), panel.background = element_rect(fill = "#FFFFFF", colour="#000000"))+
  stat_smooth(method="loess"))

这对于这个小数据集来说效果很好。但是当它变大时,线和点之间就很难区分了。这一切看起来非常相似。有没有办法只绘制每第二个或第十个数据点?

最佳答案

使用 seq() 子集 Data:

Data[seq(1, nrow(Data), 4), ] # every 4th row
Data[seq(1, nrow(Data), 2), ] # every 2nd row
# ...

关于r - 在ggplot2中绘制每个第二个数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21606315/

相关文章:

sql - RODBC查询返回零行

r - lme4::glmer 中的错误信息: "' what' must be a string or a function"

r - ggplot2 使 geom_tile 中的缺失值不为空

r - 我可以在 facet 包裹的 ggplot 中设置动态轴限制吗?

r - 为什么此 R ggplot2 代码会显示空白显示设备?

r - 使用 `subset` 函数按列名进行矩阵子集化

r - 快速获取所有矩阵列元素乘积对的方法

r 结合 ggRadar 和 facet_wrap

regex - 正则表达式匹配所有货币符号?

r - 将 grid.text 添加到 ggplot 时出错