gpt4 book ai didi

r - 顶部位置的图例未显示

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

圣诞问候!请帮忙用R根据线型绘制图例:

ggplot(mkt_liq, aes(x = Timestamp)) + geom_line(aes(y = CG), colour="green",linetype = "solid",size=1,alpha = 1,show_guide = TRUE) +  
geom_line(aes(y = FS), colour = "red",linetype = "dotdash",size=1,show_guide = TRUE) + geom_line(aes(y = MAN), colour = "black",linetype = "dotted",size=1,show_guide = TRUE)+
geom_line(aes(y = INFRA), colour = "blue",linetype = "longdash",size=1,show_guide = TRUE)+ ylab(label="Sectors") + xlab("Time")+ theme(legend.position="top")

数据集看起来像:

Timestamp   CG          FS            MAN        INFRA
9:30:00 0.680211107 0.11651278 4.792954196 0.643453697
10:00:00 0.486717157 0.106090614 2.996018087 0.387472797
10:30:00 0.458210851 0.103258739 2.802459194 0.360074724
11:00:00 0.450227036 0.103551557 2.706885909 0.365001632

最佳答案

您需要使用 reshape 和 melt 变量:

library(ggplot2)
library(reshape2)

set.seed(1234)
n <- 100
sdate <- as.POSIXct("2015-11-11 00:00:00",tz="UCT")
edate <- as.POSIXct("2015-11-11 23:59:59",tz="UCT")

mkt_liq <- data.frame(
Timestamp = as.POSIXct(runif(n,sdate,edate),tz="UCT",origin="1970-01-01"),
CG = 0.5 + rnorm(n,0,0.15),
FS = 0.1 + rnorm(n,0,0.01),
MAN = 2.8 + rnorm(n,0,0.5),
INFRA = 0.4 + rnorm(n,0,0.05)
)

# The wrong way
ggplot(mkt_liq, aes(x = Timestamp)) +
geom_line(aes(y = CG), colour="green",linetype = "solid",size=1) +
geom_line(aes(y = FS), colour = "red",linetype = "dotdash",size=1) +
geom_line(aes(y = MAN), colour = "black",linetype = "dotted",size=1)+
geom_line(aes(y = INFRA), colour = "blue",linetype = "longdash",size=1)+
ylab(label="Sectors") +
xlab("Time")+
theme(legend.position="top")

产生这个:

enter image description here

但你真正想要的是:

# The right way
mdf <- melt(mkt_liq,id=c("Timestamp"),variable.name="Sector" )

clrs <- c("CG"="green","FS"="red","MAN"="black","INFRA"="blue")
ltyp <- c("CG"="solid","FS"="dotdash","MAN"="dotted","INFRA"="longdash")

ggplot(mdf, aes(x = Timestamp,y=value,color=Sector,linetype=Sector)) +
geom_line(size=1)+
ylab(label="Sectors") +
xlab("Time")+
scale_color_manual( values=clrs )+
scale_linetype_manual( values=ltyp )+
theme(legend.position="top")

产生这个: enter image description here

完成

更新:

制作了更好的数据并添加了变量和名称以更灵活地指示颜色和线型。

关于r - 顶部位置的图例未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463410/

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