我尝试更改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"))
但是如果我将图例键“ a”和“ b”分别替换为“ a组”和“ b组”,则
scale_color_manual(values=c("red","blue"),labels=c("group a","group b"))
我得到了重复的图例,而彩色的子弹也弄错了。
怎么了?
谢谢!
答案 0 :(得分:3)
此问题是由更改颜色标签而不是形状标签引起的。因此,您需要在图形和颜色上应用标签,或者在绘制之前更改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"))
答案 1 :(得分:2)
只要在颜色和形状比例上添加相同的标签,就可以在不更改因子水平的情况下执行此操作:
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"))