Assign Fixed Colors to Categorical Variable in ggplot2 Plot in R (Example) | scale_fill_manual()
Автор: Statistics Globe
Загружено: 2023-03-07
Просмотров: 1063
How to assign pre-defined colors to qualitative variables in a ggplot2 plot in the R programming language. More details: https://statisticsglobe.com/r-assign-...
R code of this video:
data1 <- data.frame(Group = LETTERS[1:5], # Create two data frames
Count = 1:5,
stringsAsFactors = TRUE)
data2 <- data.frame(Group = LETTERS[2:6],
Count = 2:6,
stringsAsFactors = TRUE)
install.packages("ggplot2") # Install and load ggplot2 package
library("ggplot2")
ggp1 <- ggplot(data1, aes(x = Group, y = Count, fill = Group)) + # Draw first ggplot
geom_bar(stat = "Identity")
ggp1
ggp2 <- ggplot(data2, aes(x = Group, y = Count, fill = Group)) + # Draw second ggplot
geom_bar(stat = "Identity")
ggp2
my_colors <- c("red", "blue", "green", "yellow", "orange", "purple") # Create vector of colors
names(my_colors) <- levels(factor(c(levels(data1$Group), levels(data2$Group)))) # Extract all levels of both data
my_colors # Print levels and colors
my_scale <- scale_fill_manual(name = "Group", values = my_colors) # Specify scale_fill_manual
ggp1 + my_scale # First plot with manual color
ggp2 + my_scale # Second plot with manual color
Follow me on Social Media:
Facebook – Statistics Globe Page: / statisticsglobecom
Facebook – R Programming Group for Discussions & Questions: / statisticsglobe
Facebook – Python Programming Group for Discussions & Questions: / statisticsglobepython
LinkedIn – Statistics Globe Page: / statisticsglobe
LinkedIn – R Programming Group for Discussions & Questions: / 12555223
LinkedIn – Python Programming Group for Discussions & Questions: / 12673534
Twitter: / joachimschork
Music by bensound.com
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: