scale_linetype_manual 在 R 的图例中不起作用或未显示,为什么?
scale_linetype_manual is not working or shown on legend in R, why?
我想要两种线型(一种是实线,一种是虚线),并在图例中显示它(这两者都不显示),我已经尝试了下面的代码,但行没有改变,我也尝试在 scale_colour manual
之前添加 scale_linetype_manual(values=c("solid", "dashed"))
,但没有任何效果。
data<- data.frame(
Date=(1:13),
A=c(1.12,2.78,2.08,1.55,0.67,0.98,1.43,0.42,0.30,0.82,0.51,0.23,0.44),
B= c(0.10,0.07,0.04,0.05,0.10,0.08,0.12,0.05,0.02,0.11,0.06,0.05,0.11),
C= c(9.97,6.94,10.87,9.69,12.27,11.27,10.42,10.97,9.15,10.59,11.64,8.86,8.47))
LINES <- c("A" = "solid", "B" = "dashed")
ggplot(data) +
geom_line(aes(Date, A, color = "A")) +
geom_point(aes(Date, A))+
geom_line(aes(Date, B*10, color="B"))+
geom_point(aes(Date, B*10))+
scale_y_continuous(sec.axis = sec_axis(~./100, name= expression(paste("B", "(", mu, "M)"))))+
scale_color_manual(name = "", values = c("A" = "black", "B" = "black"), labels=c(A ~ (mu~M)), (B ~ (mu~M)))+
scale_linetype_manual(values=LINES)+
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")
您在使用 gggplot2
时会反复听到的一般建议是获取长格式数据。当数据为长格式时,它使得绘制数据变得非常容易。
我们去掉这里不需要的C
列,使用pivot_longer
获取长格式的数据,指定linetype
和color
作为列名并绘制他们的线图和点图。
library(tidyverse)
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
ggplot(aes(Date, value, color = name, linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100,
name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values= LINES) +
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")
我想要两种线型(一种是实线,一种是虚线),并在图例中显示它(这两者都不显示),我已经尝试了下面的代码,但行没有改变,我也尝试在 scale_colour manual
之前添加 scale_linetype_manual(values=c("solid", "dashed"))
,但没有任何效果。
data<- data.frame(
Date=(1:13),
A=c(1.12,2.78,2.08,1.55,0.67,0.98,1.43,0.42,0.30,0.82,0.51,0.23,0.44),
B= c(0.10,0.07,0.04,0.05,0.10,0.08,0.12,0.05,0.02,0.11,0.06,0.05,0.11),
C= c(9.97,6.94,10.87,9.69,12.27,11.27,10.42,10.97,9.15,10.59,11.64,8.86,8.47))
LINES <- c("A" = "solid", "B" = "dashed")
ggplot(data) +
geom_line(aes(Date, A, color = "A")) +
geom_point(aes(Date, A))+
geom_line(aes(Date, B*10, color="B"))+
geom_point(aes(Date, B*10))+
scale_y_continuous(sec.axis = sec_axis(~./100, name= expression(paste("B", "(", mu, "M)"))))+
scale_color_manual(name = "", values = c("A" = "black", "B" = "black"), labels=c(A ~ (mu~M)), (B ~ (mu~M)))+
scale_linetype_manual(values=LINES)+
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")
您在使用 gggplot2
时会反复听到的一般建议是获取长格式数据。当数据为长格式时,它使得绘制数据变得非常容易。
我们去掉这里不需要的C
列,使用pivot_longer
获取长格式的数据,指定linetype
和color
作为列名并绘制他们的线图和点图。
library(tidyverse)
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
ggplot(aes(Date, value, color = name, linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100,
name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values= LINES) +
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")