简体   繁体   English

使用r和ggplot绘制图形时如何将数据框映射为x轴?

[英]How to map the data frame as x-axis when plotting a graph with r and ggplot?

I have such a data frame df1 , to indicate the emotion status of a certain user in a time series: 我有一个数据框df1 ,以按时间序列指示某个用户的情绪状态:

0.00
0.10
0.20
0.00
0.70 
....

And another data frame df2 , to indicate the number of record in df1 in a certain day: 还有另一个数据帧df2 ,以指示某天在df1中的记录数:

2015-01-02   1
2015-01-03   2
2015-01-04   3

ie, the first value belongs to 01-02 , the second and the third value belongs to 01-03 and so on. 也就是说,第一个值属于01-02 ,第二个和第三个值属于01-03 ,依此类推。

Now I'd like the plot a point graph with date as x-axis and emotional value as y-axis. 现在,我想绘制一个点图,日期为x轴,情感价值为y轴。 How can I do that? 我怎样才能做到这一点? Furthermore, How to skip all the 0.0 value and just show the value other than zero? 此外,如何跳过所有0.0值并仅显示非零值? Thanks! 谢谢!

There are two separate steps in the solution I propose. 我建议的解决方案有两个单独的步骤。 First create a vector dates with the sequence of dates used, secondly use dplyr::filter to remove the zero values. 首先使用dates序列创建矢量dates ,然后使用dplyr::filter删除零值。

For the first step you can use a combination of lapply and rep as follows: 对于第一步,您可以使用lapplyrep的组合,如下所示:

dates <- c(lapply(seq(nrow(df2)), function(idx) rep(df2$date[idx], df2$count[idx])), recursive = TRUE)

the c(..., recursive = TRUE) is around it to convert the result to a flat vector. c(..., recursive = TRUE)在它周围,以将结果转换为平面向量。

Then combine into a data.frame filter and plot as follows: 然后合并到一个data.frame过滤器中,并进行如下绘制:

df3 <- cbind(df1, data.frame(dates = as.POSIXct(dates)))
ggplot(df3 %>% filter(state != 0.0), aes(x=dates, y = state)) + geom_point()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM