我想用 geom_line() 和 geom_rect() 創建一個圖。對于這兩個我想創造一個傳奇,但我不作業。兩者如何結合?正如您在附圖中看到的那樣,我的圖例搞砸了:顏色和形狀沒有正確顯示。
graph= data.frame(seq(as.Date("2004/01/01"), as.Date("2022/01/01"), by="month"),rnorm(217,mean=1,sd=2),rnorm(217,mean=1,sd=2),rnorm(217,mean=1,sd=2))
colnames(graph) = c("Datum","VPI","VPIF","VPIE")
plot1 = ggplot(graph, aes(x = graph$Datum))
geom_line(aes(y = graph$VPI, colour = "black"), size = 0.8)
geom_line(aes(y = graph$VPIF, colour = "red"), size = 0.8)
geom_line(aes(y = graph$VPIE, colour = "snow4"), size = 0.8)
geom_rect(aes(xmin = graph$Datum[49], xmax = graph$Datum[72], ymin = 125, ymax = 130,fill="cyan") ,alpha = 0.5)
geom_rect(aes(xmin = graph$Datum[84], xmax = graph$Datum[120], ymin = 125, ymax = 130,fill="darkolivegreen"), alpha = 0.5)
geom_rect(aes(xmin = graph$Datum[195], xmax = graph$Datum[217], ymin = 125, ymax = 130,fill="blueviolet"), alpha = 0.5)
scale_fill_manual(name=NULL,values=c("black","red","snow4","cyan","darkolivegreen","blueviolet"), labels=c("VPI","VPI Lebensmittel","VPI Energie","Weltfinanzkrise","Euro-/Schuldenkrise","Coronakrise"),aesthetics = c("colour","fill"))
theme_bw()
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 90))
labs(title = "Verbraucherpreisindex: Gesamt, Lebensmittel, Energie", subtitle = "2015=100",
y = "Prozent",
x = "Jahre")
plot1

uj5u.com熱心網友回復:
將資料從寬轉換為長。在這里,我使用pivot_longer了 tidyverse 包。但您也可以使用meltor reshape。
library(tidyverse)
data_rect <- tibble(xmin = graph$Datum[c(49,84,195)],
xmax = graph$Datum[c(72,120,217)],
ymin = 50,
ymax=53,
gr = c("1", "2", "3"))
graph %>%
pivot_longer(-1) %>%
ggplot(aes(Datum, value))
geom_line(aes(color = name))
geom_rect(data=data_rect, inherit.aes = F, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, fill=gr))

uj5u.com熱心網友回復:
像這樣的東西?
graph %>%
pivot_longer(
-Datum
) %>%
ggplot(aes(x=Datum, y = value))
geom_line(aes(color = name))
scale_color_manual(name = NULL, values = c("black", "red", "snow4"))
geom_rect(aes(xmin = graph$Datum[49], xmax = graph$Datum[72], ymin = 125, ymax = 130,fill="cyan") ,alpha = 0.5)
geom_rect(aes(xmin = graph$Datum[84], xmax = graph$Datum[120], ymin = 125, ymax = 130,fill="darkolivegreen"), alpha = 0.5)
geom_rect(aes(xmin = graph$Datum[195], xmax = graph$Datum[217], ymin = 125, ymax = 130,fill="blueviolet"), alpha = 0.5)
scale_fill_manual(name = NULL, values = c("cyan", "darkolivegreen", "blueviolet"))
theme_bw()
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 90))
labs(title = "Verbraucherpreisindex: Gesamt, Lebensmittel, Energie", subtitle = "2015=100",
y = "Prozent",
x = "Jahre")

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482738.html
下一篇:如何去除直方圖中的低頻bin
