![](/img/trans.png)
[英]R::ggplot2::geom_points: how to swap points with pie charts?
[英]R ggplot2: How to draw geom_points that have a solid color and a transparent stroke and are colored depending on color?
我想做一個散點圖 plot 每個點都有一個球體。 點及其球體都根據某些列值着色。
一個顯示我想要的最小示例:
library(ggplot2)
library(vcd) # only needed for example dataset
ggplot(Arthritis, aes(x = ID, y = Age)) +
geom_point(aes(color=Sex), size=10, alpha=.3) +
geom_point(aes(color=Treatment), size=3)
這個“解決方案”的問題在於,使用兩個geom_point
圖層似乎搞砸了傳說。 我想只有一個geom_point
圖層並使用還添加筆畫的形狀也會更有意義,所以像這樣:
ggplot(Arthritis, aes(x = ID, y = Age)) +
geom_point(aes(color=Sex, fill=Treatment), shape=21, size=5, stroke=5)
這里的傳說更有意義,但是,我不知道如何使筆觸透明。 這很重要,因為當點重疊時您將看不到任何東西。
像這樣的答案不能解決我的問題,因為它們使用恆定的顏色,因此可以使用 function alpha
。 但是,我不知道是否以及如何將它與依賴於數據的 colors 一起使用。
TL;DR:如何繪制具有純色和透明筆划但不是恆定geom_points
的 geom_points?
您在正確的軌道上認識到您可以使用 function alpha()
,並且已經意識到您不能只將alpha()
放在aes()
中。 但是,您可以在任何scale_*
函數中將alpha()
作為values=
參數傳遞。 這是使用mtcars
的示例:
ggplot(mtcars, aes(mpg, disp)) +
geom_point(
aes(color=factor(cyl), fill=factor(carb)),
shape=21, size=4, stroke=4) +
scale_color_manual(values=alpha(rainbow(3), 0.2))
一個問題是“ factor(carb)
圖例周圍的那些大黑線不適合我。超級ew。你可以使用guides()
function並使用override.aes=
來指定你的內容想要在那里顯示以及用什么替換它。在這種情況下,您可以設置color=NA
以覆蓋繼承的審美為透明(僅保留fill=
部分)。
ggplot(mtcars, aes(mpg, disp)) +
geom_point(
aes(color=factor(cyl), fill=factor(carb)),
shape=21, size=4, stroke=4) +
scale_color_manual(values=alpha(rainbow(3), 0.2)) +
guides(fill=guide_legend(override.aes = list(color=NA))) +
labs(color="cyl", fill="carb")
順便說一句,沒有簡單的方法可以將筆畫“放在” geom_point
的填充部分“后面”。 您可能可以為此編寫自己的自定義 stat/geom,但geom_point
總是先用填充繪制,然后是描邊。
解決此問題的一種簡單方法是使較大的透明圓圈根本不是點,而是實心圓圈。 這樣你就可以使用fill
美學來 label 他們。 這使用來自geom_circle
的ggforce
:
library(ggplot2)
library(vcd)
library(ggforce)
ggplot(Arthritis) +
geom_circle(aes(x0 = ID, y0 = Age, r = 2, fill = Sex), alpha = .3, colour = NA) +
geom_point(aes(x = ID, y = Age, color = Treatment), size = 3) +
coord_equal() +
scale_color_discrete(h = c(350, 190))
由代表 package (v0.3.0) 於 2020 年 7 月 1 日創建
或者制作第二個色標!
library(ggplot2)
library(vcd)
#> Loading required package: grid
library(ggnewscale)
ggplot(Arthritis, aes(x = ID, y = Age)) +
## removing stroke so it does not have this awkward border around it
geom_point(aes(color=Sex), size=10, alpha=.3, stroke = 0) +
new_scale_color()+
geom_point(aes(color=Treatment), size=3)
由代表 package (v2.0.1) 於 2022 年 6 月 15 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.