问题描述
我正在学习使用 ggplot2
,并且正在寻找最小的 ggplot2
代码,它再现了 base :: plot
result result below。我已经尝试了一些东西,并且它们都变得非常可怕,所以我正在寻找最小的表达式,并且理想地希望在x轴上有日期(它们不在那里在下面的 plot
中)。
df = data.frame(date = c(20121201,20121220,20130101,20130115,20130201),
val = c(10,5,8,20,4))
plot(cumsum(rowsum(df $ val,df $ date )),type =l)
试试这个:
ggplot(df,aes(x = 1:5,y = cumsum(val)))+ geom_line()+ geom_point()
$ b $
如果您不需要,请移除 geom_point()
想要它。
编辑:由于您需要绘制数据,因此x标签是日期,因此您可以使用 x = 1:5
并使用 scale_x_discrete
t 标签
新的 data.frame
。以 df
:
ggplot(data = df,aes(x = 1:5,y = cumsum(val)))+ geom_line()+
geom_point()+ theme(axis.text.x = element_text(angle = 90,hjust = 1))+
scale_x_discrete (labels = df $ date)+ xlab(Date)
既然你说你会有超过1美元c $ c> val 作为日期,例如,您可以先使用 plyr
来聚合它们。
$ (df,。(date),summary,val = sum(val))
require(plyr)
dd
然后,您可以继续执行相同的命令,方法是将 x = 1:5
with x = seq_len(nrow(dd))
。
I'm learning to use ggplot2
and am looking for the smallest ggplot2
code that reproduces the base::plot
result below. I've tried a few things and they all ended up being horrendously long, so I'm looking for the smallest expression and ideally would like to have the dates on the x-axis (which are not there in the plot
below).
df = data.frame(date = c(20121201, 20121220, 20130101, 20130115, 20130201),
val = c(10, 5, 8, 20, 4))
plot(cumsum(rowsum(df$val, df$date)), type = "l")
Try this:
ggplot(df, aes(x=1:5, y=cumsum(val))) + geom_line() + geom_point()
Just remove geom_point()
if you don't want it.
Edit: Since you require to plot the data as such with x labels are dates, you can plot with x=1:5
and use scale_x_discrete
to set labels
a new data.frame
. Taking df
:
ggplot(data = df, aes(x = 1:5, y = cumsum(val))) + geom_line() +
geom_point() + theme(axis.text.x = element_text(angle=90, hjust = 1)) +
scale_x_discrete(labels = df$date) + xlab("Date")
Since you say you'll have more than 1 val
for "date", you can aggregate them first using plyr
, for example.
require(plyr)
dd <- ddply(df, .(date), summarise, val = sum(val))
Then you can proceed with the same command by replacing x = 1:5
with x = seq_len(nrow(dd))
.
这篇关于使用ggplot2进行累积绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!