【问题标题】:R ggplot legend shows rectangle instead of lineR ggplot图例显示矩形而不是线
【发布时间】:2021-08-10 15:58:00
【问题描述】:

我正在尝试绘制某个平均值的正态分布密度。问题是显示矩形而不是线的图例。输出如下:

如何解决这个问题?这是我的代码:

library(dplyr)
library(ggplot2)
library(tidyr)
n=100;kseq<-c(1.5,2,3,5,7)
df1<-matrix(0,nrow=n,ncol=length(kseq))
for(i in 1:length(kseq)){
  df1[,i]<-rnorm(n,kseq[i])
}
colnames(df1)<-paste("k=",kseq,sep="")#paste("v",1:length(kseq),sep="")
df1<-as.data.frame(df1)
df2<-df1 %>% pivot_longer(cols=1:5, names_to = "group",values_to = "value") 
df2<- df2 %>% mutate( groupname=case_when(
  group=="v1"~"k=1.5",
  group=="v2"~"k=2",
  group=="v3"~"k=3",
  group=="v4"~"k=5",
  group=="v5"~"k=7"))
ggplot(df2,aes(x=value, linetype=group)) + geom_density(lwd=1.05) +
  labs(x="",y="",main="jhfu")+ labs(linetype='') +  
  theme(legend.key.size = unit(1.5, 'cm'),legend.text =  element_text(size=15),
    legend.justification = c(1, 0))+
  scale_linetype_manual(labels = colnames(df1), values = c(4,1,5,2,3)) +
  theme_light()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以将层的key_glyph 参数设置为不同类型的键,通常是draw_key_*() 系列函数之一。请参阅?draw_key 了解一些选项。

    为简洁起见的简化示例:

    library(ggplot2)
    
    ggplot(mtcars, aes(wt, linetype = factor(cyl))) +
      geom_density(key_glyph = draw_key_path)
    

    reprex package (v1.0.0) 于 2021-08-10 创建

    【讨论】:

    • 它有效。但是如何更改图例中的行长和文本?我更改了 legend.text 但没有工作。
    • 您可以更改键的宽度,例如+ theme(legend.key.width = unit(1, "cm")),您可以调整scale_linetype_discrete(labels = ...)中的图例标签。
    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2021-01-04
    • 2019-11-19
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多