ggplot图与观察结果不一致
Posted
技术标签:
【中文标题】ggplot图与观察结果不一致【英文标题】:ggplot graph inconsistent with observations 【发布时间】:2022-01-16 07:31:52 【问题描述】:我尝试创建一个可视化 4 个变量演变的图表。然而,产生的 ggplot 与观察结果不一致。这里可能有什么问题?
Data <- data.frame(
Wind = c(236,325,470,615,647,821),
Hard_coal= c(591,811,667,681,532,344),
Gas= c(883,841,472,731,678,680),
Bio = c(883,841,811,731,678,680),
year= c("2015","2016","2017","2018","2019","2020"))
#create the plot
ggp <- ggplot(Data, aes(year))+geom_line(aes(y = Wind, (size = 1.5)), group = 1)+geom_line(aes(y = Hard_coal), group = 2)+geom_line(aes(y = Gas), group = 3)+geom_line(aes(y = Bio), group = 4)+scale_x_discrete()
#情节
ggp
【问题讨论】:
【参考方案1】:您必须以tidy 格式重塑数据
library(tidyverse)
Data <- data.frame(
Wind = c(236,325,470,615,647,821),
Hard_coal= c(591,811,667,681,532,344),
Gas= c(883,841,472,731,678,680),
Bio = c(883,841,811,731,678,680),
year= c("2015","2016","2017","2018","2019","2020"))
Data %>%
pivot_longer(-year) %>%
ggplot(aes(x = year, y = value, color = name, group = name, linetype = name)) +
geom_line(size = 1.5)
由reprex package (v2.0.0) 于 2021 年 12 月 12 日创建
【讨论】:
太棒了,谢谢!【参考方案2】:我用facet_wrap()
调整了x轴
library(ggplot2)
library(reshape)
df_melt<-melt(df, id.vars=c("Year"))
df_melt<-as.data.frame(df_melt)
ggplot(df_melt, aes(x=Year, y=value, group=variable)) +
geom_line(aes(color=variable), size=3, show.legend = FALSE) +
facet_wrap(~as.factor(variable) )+
labs(x="Year", y="Value", title="") +
theme_bw()+
theme(plot.title = element_text(hjust = 0.5, face="bold", size=20, color="black")) +
theme(axis.title.x = element_text(family="Times", face="bold", size=16, color="black"))+
theme(axis.title.y = element_text(family="Times", face="bold", size=16, color="black"))+
theme(axis.text.x = element_text( hjust = 1, face="bold", size=14, color="black") )+
theme(axis.text.y = element_text( hjust = 1, face="bold", size=14, color="black") )+
theme(plot.title = element_text(hjust = 0.5))+
theme(strip.text = element_text(family="Times", face="bold", size=16, color="black"))
您可能想要突出显示特定点,请使用geom_vline()
df_melt<-melt(df, id.vars=c("Year"))
df_melt<-as.data.frame(df_melt)
ggplot(df_melt, aes(x=Year, y=value, group=variable)) +
geom_line(aes(color=variable), size=3, show.legend = FALSE) +
geom_vline(xintercept = c("2016", "2019"),col = "black", lwd = 2, lty=2) +
facet_wrap(~as.factor(variable) )+
labs(x="Year", y="Value", title="") +
theme_bw()+
theme(plot.title = element_text(hjust = 0.5, face="bold", size=20, color="black")) +
theme(axis.title.x = element_text(family="Times", face="bold", size=16, color="black"))+
theme(axis.title.y = element_text(family="Times", face="bold", size=16, color="black"))+
theme(axis.text.x = element_text( hjust = 1, face="bold", size=14, color="black") )+
theme(axis.text.y = element_text( hjust = 1, face="bold", size=14, color="black") )+
theme(plot.title = element_text(hjust = 0.5))+
theme(strip.text = element_text(family="Times", face="bold", size=16, color="black"))
【讨论】:
以上是关于ggplot图与观察结果不一致的主要内容,如果未能解决你的问题,请参考以下文章