使用R

时间:2018-03-16 11:30:20

标签: r ggplot2 legend

我有这个情节

library(dplyr)
library(ggplot2)


indexYear <- as.numeric(2000:2010)
lDLatIndex <- rep.int(4,11) 
LDLoneYear <- c(rep.int(3,5), rep.int(2,6))  
hba1catIndex <- c(rep.int(8,6), rep.int(7.5,5))
hba1coneYear <- rep.int(7,11)

LDLeffect <- data.frame(indexYear, lDLatIndex, hba1catIndex, hba1coneYear)
LDLeffect %>% 
  ggplot(., aes(x = indexYear))+
  geom_line(aes(y = lDLatIndex, colour=rgb(237/255, 115/255,116/255)), linetype = "solid" , size = 2)+
  theme_classic()+
  theme(legend.position = "bottom")+
  ylab("mean LDL cholesterol (mmol/l)                           ")+
  xlab("Calendar year")+
  theme(axis.title = element_text(size = 17, face="bold"), axis.text = element_text(size = 17, face = "bold"))+
  scale_x_continuous(breaks = seq(2000,2015, by=1),labels = c(2000,rep("",4),2005,rep("",4), 2010, rep("",4),2015))+
  scale_y_continuous(sec.axis = sec_axis(~(.-2.15)*10.929, name = "mean HbA1c (%)                                "))+
  geom_line(aes(y = LDLoneYear, colour=rgb(237/255, 115/255,116/255)), linetype = "dashed" , size = 2)+
  geom_line(aes(y = hba1coneYear, colour=rgb(152/255, 201/255,139/255)), linetype = "twodash" , size = 2)+
  geom_line(aes(y = hba1catIndex, colour=rgb(152/255, 201/255,139/255)), linetype = "F1" , size = 2)

我知道通常,最好的选择是为ggplot提供长格式的数据,但我无法让它工作。上面的情节产生了一个奇怪的传说,我无法理解它是如何到达那里的。

我看到添加的图例的名称来自颜色定义。

我想要的是用于显示每个变量的颜色和线型以及名称的图例,最好是添加自定义名称的选项。我查看了很多页面并提出了建议,但大多数都使用了长格式,我无法弄清楚因为我想要两种不同的线型和颜色。其余的不能帮助我在标签中解决这个奇怪的表达。

1 个答案:

答案 0 :(得分:2)

以下提案是否会朝着正确的方向发展?要点是:使用reshape2中的“melt”来获取ggplot友好形状的数据。使用scale_linetype_manualscale_colour_manual我明确提供颜色和线型。

library(dplyr)
library(ggplot2)
library(reshape2) ## for "melt"

indexYear <- as.numeric(2000:2010)
lDLatIndex <- rep.int(4,11) 
LDLoneYear <- c(rep.int(3,5), rep.int(2,6))  
hba1catIndex <- c(rep.int(8,6), rep.int(7.5,5))
hba1coneYear <- rep.int(7,11)

LDLeffect <- data.frame(indexYear, lDLatIndex, hba1catIndex, hba1coneYear, LDLoneYear)

melted_df <- melt(LDLeffect, id.vars="indexYear", measure.vars=c("lDLatIndex", "hba1catIndex", "hba1coneYear", "LDLoneYear"))

ggplot(melted_df, aes(x=indexYear, value, colour=variable)) + 
  geom_line(aes(linetype=variable), size = 2) + 
  scale_linetype_manual(values=c("F1", "twodash", "solid", "dashed")) +
  scale_colour_manual(values=c(rgb(237/255, 115/255,116/255), rgb(237/255, 115/255,116/255), rgb(152/255, 201/255,139/255), rgb(152/255, 201/255,139/255))) + 
  theme_classic() + 
  theme(legend.position = "bottom")+
  ylab("mean LDL cholesterol (mmol/l)")+
  xlab("Calendar year")+
  theme(axis.title = element_text(size = 17, face="bold"), axis.text = element_text(size = 17, face = "bold"))+
  scale_x_continuous(breaks = seq(2000,2015, by=1),labels = c(2000,rep("",4),2005,rep("",4), 2010, rep("",4),2015))+
  scale_y_continuous(sec.axis = sec_axis(~(.-2.15)*10.929, name = "mean HbA1c (%)"))

enter image description here