簡體   English   中英

Scale_fill_manual 不產生條件指定的顏色填充

[英]Scale_fill_manual not producing color fill specified by a condition

1:沒有問題

假設我下載storm_econ_dmg.csv

fileUrl <- "https://raw.githubusercontent.com/MichaelSodeke/DataSets/main/storm_health_dmg.csv"
download.file(fileUrl, destfile="storm_health_dmg.csv", method = "curl", mode="wb")
df1 <- read_csv("storm_health_dmg.csv") 

接下來,我用geom_bar plot 這個數據(注意fill=(max.fatal == 583) ):

p1 <- ggplot(df1, aes(x=reorder(state, max.fatal), y=max.fatal, fill=(max.fatal == 583) ))
p1 <- p1 + geom_bar(stat="identity")
p1 <- p1 + scale_fill_manual(values=c("TRUE"="seagreen3", "FALSE"="grey80"))
p1 <- p1 + coord_flip() + theme(legend.position="none")
srch <- df1$max.fatal > 50
p1 <- p1 + geom_text(data=df1[srch,], aes(label=evtype), angle=0, hjust=1.1, vjust=0.3, nudge_y=-0.1, size=2.5, fontface="bold")
p1 <- p1 + geom_text(data=df1[srch,], aes(label=max.fatal), angle=0, hjust=-1.3, vjust=0.3, nudge_y=0.1, size=2.5, fontface="bold")
p1 <- p1 + theme(panel.background = element_rect(fill = "white"),
         axis.line.x.bottom=element_line(colour="black"),
             axis.line.y.left=element_line(colour = "black"))
p1 %>% print()

從下圖中scale_fill_manual使用TRUE/FALSE值: 在此處輸入圖像描述

2:問題

現在假設我下載tornado_dmg.csv

fileUrl <- "https://raw.githubusercontent.com/MichaelSodeke/DataSets/main/tornado_dmg.csv"
download.file(fileUrl, destfile="tornado_dmg.csv", method = "curl", mode="wb")
df2 <- read_csv("tornado_dmg.csv") 

然后我用geom_jitter plot 這個數據(注意fill=(f == 5) ):

p2 <- ggplot(df2, aes(x=bgn.date, y=path.area, fill=(f == 5) ))
p2 <- p2 + geom_jitter(stat="identity", size=1)
p2 <- p2 + scale_fill_manual(values=c("TRUE"="red", "FALSE"="grey80"))
p2 %>% print()

但是,請注意scale_fill_manual在這種情況下對TRUE/FALSE值不起作用: 在此處輸入圖像描述

請解釋為什么scale_fill_manual第 1 部分有效但在第 2部分無效?

非常感謝!

嘗試按color更改fill 條可以被填充,而抖動中的點可以被着色:

library(ggplot2)
#Data
fileUrl <- "https://raw.githubusercontent.com/MichaelSodeke/DataSets/main/tornado_dmg.csv"
df2 <- read.csv(fileUrl) 
#Code
ggplot(df2, aes(x=bgn.date, y=path.area, color=(f == 5) ))+
  geom_jitter(stat="identity", size=1)+
  scale_color_manual(values=c("TRUE"="red", "FALSE"="grey80"))

Output:

在此處輸入圖像描述

我喜歡這個問題。 這是您花費大量時間試圖解決的問題之一,結果發現答案就在您面前。

問題是您使用fill作為geom_point 如果要更改點的顏色,則必須使用colorcolour (以及匹配的scale_*_manual )。 因此,您的代碼將是:

p2 <- ggplot(df2, aes(x=bgn.date, y=path.area, colour=(f == 5) ))
p2 <- p2 + geom_jitter(stat="identity", size=1)
p2 <- p2 + scale_colour_manual(values=c("TRUE"="red", "FALSE"="grey80"))
p2 %>% print()

或者,我這樣做的方式,我認為它不那么笨重:

ggplot(df2, aes(x=bgn.date, y=path.area, colour=(f == 5) ))+
  geom_point()+
  scale_fill_manual(values=c("seagreen3", "grey80"))+
  theme_classic()

我使用geom_point ,但我不知道那會是什么樣子,因為整個圖表沒有及時加載。 也許它看起來不太好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM