Masoud
Masoud

Reputation: 615

R ggplot legend shows rectangle instead of line

I am trying to plot density of normal distribution for some value of mean. The problem is the legend that shows rectangle instead line. The output is as follows:

enter image description here

How to fix this? Here is my code:

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()

Upvotes: 1

Views: 1343

Answers (1)

teunbrand
teunbrand

Reputation: 38003

You can set the key_glyph argument to the layer to a different type of key, typically one of the draw_key_*() family of functions. See ?draw_key for some options.

Simplified example for brevity:

library(ggplot2)

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

Created on 2021-08-10 by the reprex package (v1.0.0)

Upvotes: 7

Related Questions