使用希腊语表示法自定义图例标签

时间:2015-12-04 14:54:14

标签: r ggplot2

我按照Legends ggplot链接自定义图例标签。我使用他们的例子并尝试申请LINE AND POINT图的情况。目前,我可以在BAR图表的图例中添加希腊表示法,但LINE和POINT除外。

你能帮我指出这里出了什么问题吗?

library(ggplot2)
# Two variables
df <- read.table(header=TRUE, text='
 cond yval
                 A 2
                 B 2.5
                 C 1.6
                 ')

# Three variables
df2 <- read.table(header=TRUE, text='
                  cond1 cond2 yval
                  A      I 2
                  A      J 2.5
                  A      K 1.6
                  B      I 2.2
                  B      J 2.4
                  B      K 1.2
                  C      I 1.7
                  C      J 2.3
                  C      K 1.9
                  ')

# BAR IS OK 
a<- ggplot(df2, aes(x=cond1, y=yval)) + 
  geom_bar(aes(fill=cond2),   # fill depends on cond2
           stat="identity",
           colour="black",    # Black outline for all
           position=position_dodge()) # Put bars side-by-side instead of stacked
a + scale_fill_discrete(name = "Test legend" , 
                            breaks=levels(df2$cond2), 
                            labels=c(expression(alpha[1]),expression(alpha[2]), expression(alpha[3]))) # add my own legend with Greek notation 


#LEGEND FOR LINE DOES NOT WORK
# Lines and points; colour depends on cond2
b<-ggplot(df2, aes(x=cond1, y=yval)) + 
  geom_line(aes(group=cond2), colour=df2$cond2) + # colour, group both depend on cond2
  geom_point(aes(colour=cond2),               # colour depends on cond2
             size=3)    
b+ + scale_linetype_discrete(name = "Test legend" , 
                         breaks=levels(df2$cond2), 
                         labels=c(expression(alpha[1]),expression(alpha[2]), expression(alpha[3]))) # add my own legend with Greek notation

1 个答案:

答案 0 :(得分:1)

这里有一些可以帮到你的东西

b<-ggplot(df2, aes(x=cond1, y=yval)) + 
  geom_line(data=df2, aes(group=cond2, colour=cond2, linetype=cond2)) + # colour, group both depend on cond2
  geom_point(aes(colour=cond2),               # colour depends on cond2
             size=3)

b + scale_linetype_discrete(name = "Test legend" , 
                         breaks=levels(df2$cond2), 
                         labels=c(expression(alpha[1]),expression(alpha[2]), expression(alpha[3]))) + scale_colour_manual(values = c("red","blue", "green"),name="Test legend", breaks=levels(df2$cond2), labels=c(expression(alpha[1]),expression(alpha[2]), expression(alpha[3])))