Reputation: 1233
I have a dataset and I have 3 variables. One of them I want to scale by size and color but unfortunately it does color the points but instead it places a black point on top of a colored point.
example:
ggplot(df, aes(x=day_of_week, y=light, color = speed_limit, size=speed_limit)) + geom_point()
and the out_put:
Any suggestions how can I merge the color and size to 1 so that they grow?
Upvotes: 0
Views: 1931
Reputation: 4487
Here is a way to do it - create a discrete
variable and plot both color
& size
using the variables with manual scales
Note that this end up not continous scales. In my personal experience, I found that create bucket for size & colors would help to have better control over the colors and better visualization especially in the data contains outliers.
# Create some demo data
df <- data.frame(
day_of_week = rep(c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), 5),
light = rep(c("Daylight", "Darkness - no lighting", "Darkness - light unlit", "Darkness - light lit",
"Darkness - lighting unknown"), 7),
speed_limit = runif(35, 20, 70)
)
# Using ggplot2 for obvious reason
library(ggplot2)
# create the discrete variables using cut
df$speed_limit_cut <- cut(df$speed_limit, breaks = c(20, 30, 40, 50, 60, 70),
include.lowest = TRUE, right = TRUE)
levels_count <- length(levels(df$speed_limit_cut))
# Create the colors scale coresponded to the levels in cut
color_scales_fn <- colorRampPalette(c("#142D47", "#54AEF4"))
manual_color <- color_scales_fn(levels_count)
names(manual_color) <- levels(df$speed_limit_cut)
# Create the sizes scale
manual_size <- seq(1, by = 1, length.out = levels_count)
names(manual_size) <- levels(df$speed_limit_cut)
# Plot using the new variable
ggplot(df, aes(x=day_of_week, y=light, color = speed_limit_cut, size=speed_limit_cut)) +
geom_point() +
scale_size_manual(values = manual_size) +
scale_color_manual(values = manual_color)
Here is the output
Created on 2021-03-30 by the reprex package (v1.0.0)
Upvotes: 3