I am trying to change the alpha value of a polygon to depend on the value of a column in my data.
I.e., if the value of that column (topGenre) is 0, then the area should have an alpha value of 0. Any other value, and the alpha value should be 0.8.
However, when I try and do this, the alpha value for the polygons is either 0 (correctly) or 1.
My dataframe contains polygons for the UK postcode area so is hard to share in a recreatable way. I have pasted the R output for it, I hope this is enough.
I have tried using an ifelse, i.e.alpha = ifelse(topGenre == 0, 0, 0.9)
.
I have tried creating a new column in my df with cleanDF$alpha_value <- ifelse(cleanDF$topGenre == 0, 0, 0.9)
, and then doing alpha = alpha_value
.
Both of these give me the same output, where those with a value of 0 get an alpha value of 0 (fully transparent), and the others get a value of 1 (fully opaque).
I’ve also tried using scale_alpha_discrete
, but I’m really unsure as to the syntax of this. Trying scale_alpha_discrete(ifelse(topGenre == 0, 0, 0.9),name="Transparency")
and scale_alpha_discrete(name="Transparency")
both throw me the same error of Error in
train_discrete(): ! Continuous value supplied to a discrete scale
.
Here is my full ggplot code:
# 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))
Here is a snippet of my dataframe:
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
Jason Cooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.