R ggplot2引入轻微平滑到只有少数数据点的线图 [英] R ggplot2 introduce slight smoothing to a line graph with only a few datapoints

查看:433
本文介绍了R ggplot2引入轻微平滑到只有少数数据点的线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道这是否是一个编程问题...



如果我有下面的数据,这会产生一个'尖刻的'图表,喜欢使用ggplot2生成一个稍微平滑的一个,我怎么最优雅地去谈论它。通常的平滑方法消除了太多的信息。我正在考虑的一种方法是在当前集之间插入额外的两个数据点,然后采用2个周期的移动平均值或其他值。这似乎是一个很难的手动编码,所以我会采取一个答案,作为最后的手段优雅自动化。

  a = data.frame(year = paste('FY',2001:2012,sep ='。'),values = rnorm(12))
library(ggplot2)
 <$> 

c $ c> ggplot(a,aes(x = year,y = values,group = 1))+ geom_line()

这从图表中删除了太多的信息

  ggplot(a,aes(x = year,y = values,group = 1))+ stat_smooth(se = F)

谢谢

解决方案

您可以尝试多项式。由于x轴变量具有12个唯一值,因此可以使用多项式达到11度。此外,您应该使用x轴的连续标度来获得平滑的曲线。



下面是一个8阶多项式的例子:

  ggplot(a,aes(x = year,y = values,group = 1))+ 
stat_smooth(aes(x = seq长度(唯一(年)))),#连续x轴
se = F,method =lm,公式= y〜poly(x,8))+
scale_x_continuous(breaks = seq (长度(唯一(一年$))),
labels = levels(一年$))#原始标签

这里, method =lm表示使用线性模型。 poly 函数的第二个参数指定程度。


Not sure if this is a programming question or not...

If I have the data below, which produces a 'spiky' chart, and I'd like to produce a slightly smoothed one using ggplot2 how do I go about it most elegantly. The usual smoothing methods remove too much information. One way I'm considering is to interpolate an extra two data points in between the current set and then take a 2 period moving average or something. That seems like a lot of hard work to code manually so I'll take an answer that automates that elegantly as a last resort.

a=data.frame(year=paste('FY',2001:2012,sep='.'),values=rnorm(12))
library(ggplot2)

As you can see this is spiky and visually unappealing

ggplot(a,aes(x=year,y=values,group=1))+geom_line() 

And this removes too much information from the graph

ggplot(a,aes(x=year,y=values,group=1))+stat_smooth(se=F) 

Thanks

解决方案

You can try a polynomial. Since the x-axis variable has 12 unique values, you can use polynomials up to the 11th degree. Furthermore, you should use a continuos scale for the x-axis to achieve a smooth curve.

Here's an example of an 8th-order polynomial:

ggplot(a, aes(x = year, y = values, group = 1))+
  stat_smooth(aes(x = seq(length(unique(year)))), # continuous x-axis
              se = F, method = "lm", formula = y ~ poly(x, 8)) +
  scale_x_continuous(breaks = seq(length(unique(a$year))), 
                     labels = levels(a$year)) # original labels

Here, method = "lm" means, that a linear model is used. The second argument of the poly function specifies the degree.

这篇关于R ggplot2引入轻微平滑到只有少数数据点的线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆