【问题标题】:How to solve the sawtooth pattern in ggplot?如何解决ggplot中的锯齿图案?
【发布时间】:2014-05-19 01:44:49
【问题描述】:

我有这个数据集:

##     fips      SCC Pollutant Emissions  type year
## 4  09001 10100401  PM25-PRI    15.714 POINT 1999
## 8  09001 10100404  PM25-PRI   234.178 POINT 1999
## 12 09001 10100501  PM25-PRI     0.128 POINT 1999
## 16 09001 10200401  PM25-PRI     2.036 POINT 1999
## 20 09001 10200504  PM25-PRI     0.388 POINT 1999
## 24 09001 10200602  PM25-PRI     1.490 POINT 1999


'data.frame':   2096 obs. of  6 variables:
 $ fips     : chr  "24510" "24510" "24510" "24510" ...
 $ SCC      : chr  "10100601" "10200601" "10200602" "30100699" ...
 $ Pollutant: chr  "PM25-PRI" "PM25-PRI" "PM25-PRI" "PM25-PRI" ...
 $ Emissions: int  6 78 0 10 10 83 6 28 24 40 ...
 $ type     : chr  "POINT" "POINT" "POINT" "POINT" ...
 $ year     : int  1999 1999 1999 1999 1999 1999 1999 1999 1999 1999 ...

fips:表示美国县的五位数字(表示为字符串)
SCC:由数字字符串表示的源名称(见源代码分类表)
Pollutant:表示污染物的字符串
Emissions:PM2.5排放量,以吨为单位
type:源的类型(点、非点、道路或非道路)
年份:记录的排放年份

我正在尝试在 ggplot 中绘制一个图,以查看排放量是否随源类型逐年增加或减少;我还想添加一个线性模型来显示趋势。

这是我到目前为止所做的:

GGplotGraph <- ggplot(PM25Baltimore, aes(x = year, y = Emissions, group = year, colour = type))

GGplotGraph <- GgplotGraph + geom_line() + facet_wrap(~ type) + theme(legend.position = "none")

GGplotGraph <- GgplotGraph + geom_smooth(method = "lm", formula = Emissions ~ year , se = FALSE, aes(group = 1)

这是我得到的图表,但我希望这些线从 1999 年到 2008 年是连续的。

在对该主题进行了一些研究之后,我了解到这是因为grouping 做错了。我尝试了各种组合,我将类型列转换为因子,但仍然不起作用。

我遇到的另一个问题是线性模型。我收到此错误:

Error in model.frame.default(formula = formula, data = data, weights = weight,  : 
  variable lengths differ (found for '(weights)')
Error in if (nrow(layer_data) == 0) return() : argument is of length zero

我找到了here一些解释,但我在调试、回溯或恢复方面的技能非常有限。

我想要一些关于如何继续或下一步尝试什么的建议。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    首先我创建了一些测试数据,因为您的示例太短而无法重现

    set.seed(18)
    PM25Baltimore<-data.frame(
        type = rep(c("Non-Road","Nonpoint","on-road","point"), each=10*10),
        year = rep(1999:2008, 10*4),
        Emissions = runif(10*4*10, 0,500)
    )
    

    所以我将使用stat_summary 而不是group 来折叠每种类型/年份的多个观察值以使用平均值。我认为group=year 是导致您的“锯齿”问题的原因。这会给我以下情节

    ggplot(PM25Baltimore, aes(year, Emissions, color=type)) + 
        facet_wrap(~ type) + theme(legend.position = "none") + 
        stat_summary(fun.y="mean", geom="line") + 
        geom_smooth(method="lm", se=FALSE, linetype=3, color="black")
    

    【讨论】:

    • 谢谢!有效。我还认为由于字符变量,我在绘图时遇到了问题。他们应该是因素。无论如何,现在一切都很好。:)
    猜你喜欢
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    相关资源
    最近更新 更多