繁体   English   中英

更改 ggplot2 中图例中的键标签

[英]change the key labels in a legend in ggplot2

我尝试更改ggplot上的关键标签,但没有成功。 当我在scale_color_manual行指示标签时,图例出现重复。 我的错误在哪里?

考虑示例:

mydata <- data.frame(
year=as.integer(rep(2010:2020,each=2)),
type=rep(c("a","b"),11),
value=c(617,186,546,241,430,217,349,188,286,141,446,166,442,167,424,210,421,182,405,190,432,194))

ggplot(mydata,aes(year,value,group=type))+
    theme_bw()+
    theme(
        axis.text=element_text(size=16),
        axis.title=element_text(size=18),
        legend.position=c(.75,.885),
        legend.key = element_rect(color = "white", fill = NA),
        legend.key.size = unit(1, "cm"),
        legend.title=element_blank(),
        legend.text=element_text(size=20)
    )+
    labs(x="year",y="number")+
    geom_point(aes(color=type,shape=type),size=3)+
    scale_x_continuous(breaks = seq(min(mydata$year),max(mydata$year), by = 2))+
    scale_shape_manual(values=c(15,19))+
    scale_color_manual(values=c("red","blue"))

但是如果我用“group a”和“group b”替换图例键“a”和“b”

scale_color_manual(values=c("red","blue"),labels=c("group a","group b"))

我得到了重复的图例,彩色的子弹变错了。

错误的情节

怎么了?

谢谢!

该问题是由更改颜色标签而不是形状标签引起的。 因此,您要么需要将标签应用于形状和颜色,要么在绘图之前更改type因子标签。

library(ggplot2)
library(dplyr)

mydata %>%
  mutate(type = factor(type, labels = c("group a","group b"))) %>%
  ggplot(aes(year,value))+
  theme_bw()+
  theme(
    axis.text=element_text(size=16),
    axis.title=element_text(size=18),
    legend.position=c(.75,.885),
    legend.key = element_rect(color = "white", fill = NA),
    legend.key.size = unit(1, "cm"),
    legend.title=element_blank(),
    legend.text=element_text(size=20)
  )+
  labs(x="year",y="number")+
  geom_point(aes(color=type,shape=type),size=3)+
  scale_x_continuous(breaks = seq(min(mydata$year),max(mydata$year), by = 2))+
  scale_shape_manual(values=c(15,19))+
  scale_color_manual(values=c("red","blue"))

在此处输入图片说明

您可以在不更改因子水平的情况下执行此操作,前提是您向颜色和形状比例添加相同的标签:

ggplot(mydata,aes(year,value,group=type))+
    theme_bw()+
    theme(
        axis.text=element_text(size=16),
        axis.title=element_text(size=18),
        legend.position=c(.75,.885),
        legend.key = element_rect(color = "white", fill = NA),
        legend.key.size = unit(1, "cm"),
        legend.title=element_blank(),
        legend.text=element_text(size=20)
    )+
    labs(x="year",y="number")+
    geom_point(aes(color=type,shape=type),size=3)+
    scale_x_continuous(breaks = seq(min(mydata$year),max(mydata$year), by = 2))+
    scale_shape_manual(values=c(15,19), labels = c("group a", "group b")) +
    scale_color_manual(values=c("red","blue"), labels = c("group a", "group b"))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM