[英]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.