我有一個資料集,我試圖為按 Species Group 分組的同一變數(Den Volume)制作 3 個圖表。我分解了 Species Group Column 以控制顯示的順序,但在 line 和 fill 之間不保留顏色順序。
這是代碼片段:
ggthemr("flat")
cts_table_Complete$SppGroups <-
factor(cts_table_Complete$SppGroups,
levels = c("None",
"Arachnids",
"Herptiles (excl. CTS)",
"Kangaroo Rat",
"Rodents")
) #reorder so "None" is first
vol_gg_bar <- ggplot(cts_table_Complete, aes(x = Den.Volume.in3,
fill = SppGroups))
scale_x_continuous(limits = c(0,200))
geom_bar(stat = 'bin', alpha = 0.8)
theme(legend.position = "left")
labs(fill = "Species Group",
x = "Den Volume (Cubic Inches)",
y = "Number of Observations")
vol_gg_dense <- ggplot(cts_table_Complete, aes(x = Den.Volume.in3,
color = SppGroups))
scale_x_continuous(limits = c(0, 200))
theme(legend.position = "left")
labs(fill = "Species Group",
x = "Den Volume (Cubic Inches)",
y = "Porportion of Observations")
geom_density(alpha = 0.6, size = 2)
scale_color_discrete(aesthetics = c("colour"))
grid.arrange(vol_gg_bar, vol_gg_dense, ncol=2)
不幸的是,條形圖的填充是這樣的:

密度圖上的線條如下所示:

我想更改線條以匹配填充,所以因為我也有一個使用填充顏色的箱形圖,我希望所有 3 個都匹配。
uj5u.com熱心網友回復:
問題是ggthemr("flat")覆寫了默認的 ggplot2 調色板。但是,看起來這并不適用于所有情況。
但根據檔案
為避免這種情況并在這些情況下繼續使用 ggthemr 顏色,請在 ggplot 呼叫中添加 scale_colour_ggthemr_d() 圖層。
因此,添加scale_colour_ggthemr_d()而不是scale_color_discrete解決您的問題:
使用mtcars示例資料:
library(ggthemr)
#> Loading required package: ggplot2
library(ggplot2)
library(gridExtra)
ggthemr("flat")
vol_gg_bar <- ggplot(mtcars, aes(mpg, fill = factor(am)))
scale_x_continuous(limits = c(0,200))
geom_bar(stat = 'bin', alpha = 0.8)
theme(legend.position = "left")
labs(fill = "Species Group",
x = "Den Volume (Cubic Inches)",
y = "Number of Observations")
vol_gg_dense <- ggplot(mtcars, aes(mpg, colour = factor(am)))
scale_x_continuous(limits = c(0, 200))
theme(legend.position = "left")
labs(fill = "Species Group",
x = "Den Volume (Cubic Inches)",
y = "Porportion of Observations")
geom_density(alpha = 0.6, size = 2)
scale_colour_ggthemr_d()
grid.arrange(vol_gg_bar, vol_gg_dense, ncol=2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> Warning: Removed 4 rows containing missing values (geom_bar).

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450738.html
