I'm trying to create a range of colors to reflect degrees of intensity in my crosstab plot. For example, values 0-33 get assigned light green, 34-66 get assigned a standard green, and 67-100 get assigned a forest green. I have only been able to figure out how to make the dots all one color. Is there a command to do this?
#Load ggplot2
library(ggplot2)
#Specify foods and countries
foods <- c("popcorn", "carrots", "licorice", "eggs", "noodles", "walnuts")
nations <- c("Portgual", "Macedonia", "Germany", "France", "Denmark", "Belgium")
#Create the data frame
crosstab <- expand.grid(foods, nations)
crosstab$value <- c(12.2, 5.4, 11.1, 33.1, 19.7, 6.5, 22.2, 21.1, 58.7, 91.4, 38.4, 14.0, 23.5, 34.2, 43.1, 51.5, 16.7, 19.1, 11.1, 28.9, 26.1, 14.1, 13.0, 41.2, 56.2, 32.1, 48.9, 47.3, 17.1, 46.5, 21.2,
51.1, 62.1, 14.8, 53.5, 11.8)
#Plot the visualization
final_plot <- ggplot(crosstab, aes(Var1, Var2)) + geom_point(aes(size = value), colour = "lavender") + theme_bw() + xlab("") + ylab("")
#Add design elements
final_plot + scale_size_continuous(range = c(10, 25)) + geom_text(aes(label = value)) +
theme(legend.position = "none") +
theme(axis.text.x = element_text(size = 10)) +
theme(axis.text.y = element_text(size = 10)) +
theme(axis.ticks = element_blank()) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank())
You can create different groups based on their value using cut
function and pass this new variable as color
argument into your aes
. Then, using scale_color_manual
, you can set appropriate colors:
library(dplyr)
library(ggplot2)
crosstab %>% mutate(CutColor = cut(value, breaks = c(0,33,66,100))) %>%
ggplot(aes(x = Var1, y = Var2))+
geom_point(aes(size = value, color = CutColor))+
geom_text(aes(label = value)) +
scale_size_continuous(range = c(10, 25)) +
scale_color_manual(values = c("lightgreen","green","forestgreen"))+
theme(legend.position = "none",
axis.text.x = element_text(size = 10),
axis.text.y = element_text(size = 10),
axis.ticks = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank())
Does it answer your question ?