gpt4 book ai didi

r - r 中四个变量的折线图在一张图中

转载 作者:行者123 更新时间:2023-12-05 00:51:01 25 4
gpt4 key购买 nike

我想创建一个折线图,显示 2009 年至 2019 年间五种空气污染物的趋势。

<头>
年份 二氧化碳 二氧化氮 O3 PM2.5
2009 30 18 20 30
2010 32 16 22 20
2011 33 16 24 20
2012 32 15 25 22
2013 34 14 27 24
2014 36 14 28 22
2015 38 13 29 20
2016 39 13 30 18
2017 40 12 32 16
2018 44 13 34 15
2019 45 11 38 14

我给出了那个代码,但它是一个直方图,我想要一个折线图,所有四个都在同一个图中。

df %>%
ggplot(aes(x = Year, y = n, fill = airpollutants)) +
geom_col() +
facet_wrap(~Year) + ggtitle("trend of airpollutants")

我想要这个输出: https://cdn.ablebits.com/_img-blog/line-graph/line-graph-excel.png

最佳答案

您可以像这样将数据从宽到长和 color 每一种空气污染物 reshape :

df <- read.table(text = "Year   CO2 NO2 O3  PM2.5
2009 30 18 20 30
2010 32 16 22 20
2011 33 16 24 20
2012 32 15 25 22
2013 34 14 27 24
2014 36 14 28 22
2015 38 13 29 20
2016 39 13 30 18
2017 40 12 32 16
2018 44 13 34 15
2019 45 11 38 14
", header = TRUE)

library(ggplot2)
library(dplyr)
library(reshape)
df %>%
melt(id = "Year") %>%
mutate(variable = as.factor(variable)) %>%
ggplot(aes(x = Year, y = value, colour = variable)) +
geom_line() +
labs(colour = "airpollutants") +
ggtitle("trend of airpollutants")

reprex package 于 2022-07-26 创建(v2.0.1)

关于r - r 中四个变量的折线图在一张图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73123071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com