How to set legend alpha with ggplot2
Update With the release of version 0.9.0, one can now override aesthetic values in the legend using override.aes
in the guides
function. So if you add something like this to your plot:
+ guides(colour = guide_legend(override.aes = list(alpha = 1)))
that should do it.
I've gotten around this by doing a duplicate call to the geom using an empty subset of the data and using the legend from that call. Unfortunately, it doesn't work if the data frame is actually empty (e.g. as you'd get from subset(diamonds,FALSE)
) since ggplot2 seems to treat this case the same as it treats NULL
in place of a data frame. But we can get the same effect by taking a subset with only one row and setting it to NaN
on one of the plot dimensions, which will prevent it from getting plotted.
Based off Chase's example:
# Alpha parameter washes out legend:
gp <- ggplot() + geom_point(data=diamonds, aes(depth, price, colour=clarity), alpha=0.1)
print(gp)
# Full color legend:
dummyData <- diamonds[1, ]
dummyData$price <- NaN
#dummyData <- subset(diamonds, FALSE) # this would be nicer but it doesn't work!
gp <- ggplot() +
geom_point(data=diamonds, aes(depth, price, colour=clarity), alpha=0.1, legend=FALSE) +
geom_point(data=dummyData, aes(depth, price, colour=clarity), alpha=1.0, na.rm=TRUE)
print(gp)
R ggplot2 scale alpha discrete to display in legend
One option to achieve your desired result would be to set the fill color for the alpha
legend via the override.aes
argument of guide_legend
.
Making use of mtcars
as example data:
library(ggplot2)
ggplot(mtcars, aes(x = cyl, y = mpg)) +
geom_boxplot(aes(fill = factor(cyl), alpha = factor(am))) +
scale_alpha_discrete(range = c(0.3, 0.9), guide = guide_legend(override.aes = list(fill = "black"))) +
scale_fill_brewer(palette='Set1') +
theme_classic(base_size=10) +
guides(fill = "none")
#> Warning: Using alpha for a discrete variable is not advised.
Remove point transparency in ggplot2 legend
You can use function guides()
and override.aes=
to set alpha value just for legend entries.
ggplot(df) + geom_point(aes(x, y, color=z), alpha=0.1)+
guides(colour = guide_legend(override.aes = list(alpha=1)))
ggplot2: Change Alpha of scale_color_viridis_c but not legend
You can simply add your alpha to the geom_point()
rather than the colour scale. Below is a reproducable example highlighting the difference between your current approach and the correct way to acchieve what you have asked, i.e., 'How can I change the alpha of my color scale while retaining full visibility and the actual scale in the legend?'
library(ggplot2)
library(vctrs)
###Generate Mock Data ###
df<- data_frame(y=seq(1:100), x=seq(1:100), z=seq(1:100))
###Plot with Alpha = 0 showing points and legend disappears###
ggplot(df,aes(x,y,color=z)) +
geom_point()+
scale_color_viridis_c(alpha=0.00)
###Plot with Alpha = 0.1 showing points and legend disappears###
ggplot(df,aes(x,y,color=z)) +
geom_point()+
scale_color_viridis_c(alpha=0.1)
###Plot with Alpha = 0 showing points disappear while legend remains visible###
ggplot(df,aes(x,y,color=z)) +
geom_point(alpha=0.00)+
scale_color_viridis_c()
###Plot with Alpha = 0 showing points disappear while legend remains visible###
ggplot(df,aes(x,y,color=z)) +
geom_point(alpha=0.1)+
scale_color_viridis_c()
How to create legend with differing alphas for multiple geom_line plots in ggplot2 (R)
You need to put alpha and size categories in aes like you put color. Then, you can use scale_alpha_manual and scale_size_manual with respect to your need. Also, by that there is no need for creating data2a and data2b.
See below code:
ggplot(data2, aes(x=year,y=students,color=schools,group=schools,
alpha=schools, size = schools)) +
theme_classic() +
geom_line() +
scale_color_manual(values=c("red","orange","green","skyblue","aquamarine","purple",
"pink","blue","brown","black")) +
scale_alpha_manual(values = c(0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3,NA, 0.3, 0.3)) +
#for the default alpha, you can write 1 or NA
scale_size_manual(values= c(1,1,1,1,1,1,1,1.5,1,1))
The code brings this plot. Please click.
I hope it will be useful.
ggplot2: combine fill and alpha legends
Instead of making use of both fill
and alpha
one option would be to make use of just fill
like so:
- Add a column with your desired fill colors to your dataset using e.g. a
left_join
. - Manually compute your
alpha
levels using e.g.cut
. - Adjust the transparency of th colors according to the alpha values using
colorspace::adjust_transparency
- Map the resulting colors on the
fill
aes and make use ofscale_fill_identity
. Addguide=guide_legend
to get a legend.
library(ggplot2)
library(dplyr)
library(colorspace)
cols <- c(negative = "midnightblue", positive = "yellow1", zero = "red4")
cols <- tibble::enframe(cols, name = "binary_slope", value = "fill")
dummy <- left_join(dummy, cols, by = "binary_slope")
dummy <- mutate(dummy,
alpha = cut(value, breaks = c(0, 0.4, 0.6, 0.8, 1), labels = c(0.4, 0.6, 0.8, 1)),
alpha = as.numeric(as.character(alpha)),
fill = colorspace::adjust_transparency(fill, alpha)
)
ggplot(dummy, aes(x = model, y = longvarname)) +
geom_tile(aes(fill = fill)) +
scale_fill_identity(guide = guide_legend()) +
facet_grid(vargrp ~ ., scales = "free_y", space = "free_y") +
xlab("Model") +
ylab("Variable") +
theme(
panel.background = element_blank(),
axis.text.x = element_text(angle = 45, hjust = 1),
strip.text.y = element_blank(),
axis.ticks = element_blank()
)
Related Topics
How to Add Annotations Below the X Axis in Ggplot2
Convert 12 Hour Character Time to 24 Hour
Propagating Data Within a Vector
Ggplot2 Make Missing Value in Geom_Tile Not Blank
Grouped Operations That Result in Length Not Equal to 1 or Length of Group in Dplyr
R: Eval(Parse(...)) Is Often Suboptimal
Rstudio Is Duplicating Commands in the Command Line
Applying a Function to Two Lists
Remove All Duplicates Except Last Instance
R Dplyr Rowwise Mean or Min and Other Methods
R: How to Use Coord_Cartesian on Facet_Grid with Free-Ranging Axis
Replace Missing Values (Na) in One Data Set with Values from Another Where Columns Match
Align Multiple Ggplot2 Plots with Grid
Efficient String Similarity Grouping