R ggplot 条件 alpha 值未按预期运行

问题描述 投票:0回答:1

我正在尝试更改多边形的 alpha 值以取决于数据中列的值。 即,如果该列 (topGenre) 的值为 0,则该区域的 alpha 值应为 0。任何其他值,alpha 值应为 0.8。 但是,当我尝试执行此操作时,多边形的 alpha 值为 0(正确)或 1。 我的数据框包含英国邮政编码区域的多边形,因此很难以可重新创建的方式共享。我已经粘贴了 R 输出,我希望这已经足够了。

我尝试过使用 ifelse,即

alpha = ifelse(topGenre == 0, 0, 0.9)
。 我尝试使用
cleanDF$alpha_value <- ifelse(cleanDF$topGenre == 0, 0, 0.9)
在我的 df 中创建一个新列,然后执行
alpha = alpha_value
。 这两个都给我相同的输出,其中值为 0 的输出的 alpha 值为 0(完全透明),其他的输出值为 1(完全不透明)。 我也尝试过使用
scale_alpha_discrete
,但我真的不确定它的语法。尝试
scale_alpha_discrete(ifelse(topGenre == 0, 0, 0.9),name="Transparency")
scale_alpha_discrete(name="Transparency")
都给我带来了
Error in 
train_discrete()
: ! Continuous value supplied to a discrete scale
.

相同的错误

这是我完整的 ggplot 代码:

# Manually create a bounding box
bbox<-make_bbox(c(-2,-1.8),c(52.53,52.43),f=0.05)

# Create the basemap
a <- get_map(bbox,maptype="stamen_toner_lite",source="google") # Only works using google as a source which it then corrects

# Create the map
ggplot(cleanDF) +
  annotation_raster(a, xmin=-2,xmax=-1.8,ymin=52.43,ymax=52.53) +
  geom_sf(aes(fill = factor(topGenre), geometry = geometry, alpha = ifelse(topGenre == 0, 0, 0.9))) +
  scale_fill_discrete(name="Most common music genre") +
  labs(title = "Choropleth Map of UK Postcode Areas by topGenre", alpha = "Transparency") +
  theme_minimal() +
  coord_sf(xlim = c(-2, -1.8), ylim = c(52.43, 52.53))

这是我的数据框的片段:

    name topGenre                       geometry alpha_value
1   B1 1       24 MULTIPOLYGON (((-1.899073 5...         0.9
2   B1 2        0 MULTIPOLYGON (((-1.913425 5...         0.0
3   B1 3       43 MULTIPOLYGON (((-1.914898 5...         0.9
4  B10 0        0 MULTIPOLYGON (((-1.876766 5...         0.0
5  B10 9        0 MULTIPOLYGON (((-1.832487 5...         0.0
r ggplot2
1个回答
0
投票

我认为 ggplot 正在将您提供的值(0 和 0.9)映射到默认范围 0.1 到 1。要覆盖此值,请尝试:

+ scale_alpha_continuous(range = c(0., 0.9))
© www.soinside.com 2019 - 2024. All rights reserved.