R语言 更改直方图和密度图ggplot2中的图例时出错

idfiyjo8  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(160)

我有下一个数据集:

structure(list(working_hours = c("Whours_after", "Whours_after", 
"Whours_before", "Whours_before", "Whours_before", "Whours_before", 
"Whours_after", "Whours_after", "Whours_after", "Whours_after", 
"Whours_after", "Whours_before", "Whours_before", "Whours_after", 
"Whours_after", "Whours_before", "Whours_after", "Whours_after", 
"Whours_before", "Whours_after", "Whours_after", "Whours_before", 
"Whours_before", "Whours_after", "Whours_before", "Whours_before", 
"Whours_after", "Whours_after", "Whours_before", "Whours_after"
), value = c(12.6000003814697, 21, NA, NA, 42, 42, 42, 21, 42, 
42, 0, 0, 42, 42, 0, 42, 42, 36.9599990844727, 16.7999992370605, 
8.39999961853027, 42, 42, 42, 0, 29.3999996185303, 10.5, 42, 
42, 0, 0)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-30L))

我已经创建了下一个图直方图和两个密度。但我不知道如何改变图例中的数字:

p<-ggplot(datas,aes(x=value,fill=working_hours,color=working_hours))+
  geom_histogram(aes(y=..density..),alpha=0.5,binwidth = 3,position="identity")+
  geom_density(alpha=.3)+labs(title="Histrogram")+
  scale_fill_manual(values=c( "#ED0000FF","#4668BDFF"))

我在互联网上找到了我需要包括的信息

p+scale_fill_manual(values=c( "#ED0000FF","#4668BDFF"))+scale_fill_discrete(name = "Dose", labels = c("A", "B"))

但是当我把它包括在内时,我得到了这个:

eimct9ow

eimct9ow1#

第一个问题是,通过添加scale_fill_discrete,您将覆盖scale_fill_manual。第二,您同时在colorfill美学上进行Map。但是,通过仅为fill比例指定namelabelscolorfill的图例将不再合并,最终将得到两个不同的图例,一个用于color,另一个用于fill
要解决第一个问题,请删除scale_fill_discrete,并通过scale_fill_manualnamelabels参数分配标签。
要解决第二个问题,您必须添加具有相同调色板,名称和标签的相应scale_color_manual,或者通过将aesthetics = c("fill", "color")添加到scale_fill_manual,将fill比例应用于colorfill美学:

library(ggplot2)

ggplot(datas, aes(x = value, fill = working_hours, color = working_hours)) +
  geom_histogram(
    aes(y = after_stat(density)),
    alpha = 0.5, binwidth = 3, position = "identity"
  ) +
  geom_density(alpha = .3) +
  labs(title = "Histrogram") +
  scale_fill_manual(
    values = c("#ED0000FF", "#4668BDFF"),
    aesthetics = c("fill", "color"),
    name = "Dose", labels = c("A", "B")
  )

相关问题