Barcharts: grouping bars using facet_wrap - r

I want to group these bars by the variable "env".
ggplot(dat, aes(x = Sample, fill = phylum, y = Abundance)) +
geom_bar(position="fill", stat = "identity") + theme_bw() +
facet_wrap( ~ env) +
theme(axis.text.x = element_text(angle = 90, size = 13, colour = "black", vjust = 0.5, hjust = 1), axis.title.x = element_text(size = 15),
axis.text.y = element_text(size = 13, vjust = 0.5, hjust = 1), axis.title.y = element_text(size = 15), legend.title = element_text(size = 15),
legend.text = element_text(size = 15, colour = "black")) +
ggtitle("Minion samples: Proteobacteria Phyla") + scale_y_continuous(labels = percent_format(), limits=c(0,1)) +
scale_fill_manual(values = c("Acidobacteria"="#3288bd",
"Actinobacteria" = "#99d594",
"Candidatus Rokubacteria" = "#74c476",
"Chloroflexi"= "#e6f598",
"Planctomycetes"="#fee08b",
"Proteobacteria" = "#fc8d59",
"Verrucomicrobia" = "#a50f15",
"Taxa less than 1%" = "#d53e4f"))
I get this:
I would like to have an unique x-axis and get rid of these empty spaces. Is there an other option beside facet_wrap?
Thanks

As per the comments, indeed using facet_wrap(~env, scales = "free, nrow =1) will solve your issue.
Moreover, you might want to have an equal width for the histograms, in this case you can use facet_grid and the space argument to have something like this:
ggplot(dat, aes(x = Sample, fill = phylum, y = Abundance)) +
geom_bar(position="fill", stat = "identity") + theme_bw() +
facet_grid(. ~ env, scales = "free", space = "free")+
theme(axis.text.x = element_text(angle = 90, size = 13, colour = "black", vjust = 0.5, hjust = 1), axis.title.x = element_text(size = 15),
axis.text.y = element_text(size = 13, vjust = 0.5, hjust = 1), axis.title.y = element_text(size = 15), legend.title = element_text(size = 15),
legend.text = element_text(size = 15, colour = "black")) +
ggtitle("Minion samples: Proteobacteria Phyla") + scale_y_continuous(labels = percent_format(), limits=c(0,1)) +
scale_fill_manual(values = c("Acidobacteria"="#3288bd",
"Actinobacteria" = "#99d594",
"Candidatus Rokubacteria" = "#74c476",
"Chloroflexi"= "#e6f598",
"Planctomycetes"="#fee08b",
"Proteobacteria" = "#fc8d59",
"Verrucomicrobia" = "#a50f15",
"Taxa less than 1%" = "#d53e4f"))
Whereas, facet_wrap(~ env, scales = "free", nrow = 1) results in unequal width distribution when free on one row:
ggplot(dat, aes(x = Sample, fill = phylum, y = Abundance)) +
geom_bar(position="fill", stat = "identity") + theme_bw() +
facet_wrap(~ env, scales = "free", nrow = 1)+
theme(axis.text.x = element_text(angle = 90, size = 13, colour = "black", vjust = 0.5, hjust = 1), axis.title.x = element_text(size = 15),
axis.text.y = element_text(size = 13, vjust = 0.5, hjust = 1), axis.title.y = element_text(size = 15), legend.title = element_text(size = 15),
legend.text = element_text(size = 15, colour = "black")) +
ggtitle("Minion samples: Proteobacteria Phyla") + scale_y_continuous(labels = percent_format(), limits=c(0,1)) +
scale_fill_manual(values = c("Acidobacteria"="#3288bd",
"Actinobacteria" = "#99d594",
"Candidatus Rokubacteria" = "#74c476",
"Chloroflexi"= "#e6f598",
"Planctomycetes"="#fee08b",
"Proteobacteria" = "#fc8d59",
"Verrucomicrobia" = "#a50f15",
"Taxa less than 1%" = "#d53e4f"))
Data
library(scales)
library(ggplot2)
set.seed(18)
dat = data.frame(
env = factor(rep(sample(c("Dry", "Fossil", "Wet", "Soil"), size = 25, prob = c(3,2,18,2), replace = T), each=8), levels =c("Dry", "Fossil", "Wet", "Soil")),
Sample = rep(paste0("Sample_",letters[1:25]), each=8),
phylum = rep(c("Acidobacteria", "Actinobacteria","Candidatus Rokubacteria","Chloroflexi","Planctomycetes", "Proteobacteria", "Verrucomicrobia","Taxa less than 1%"),times = 25),
Abundance = runif(200,0,1))

Related

In ggplot2, how can I use multi-row x-axis labels with facet_wraps?

I have multi-row x-axis labels such that the first row is month and the second row is year. However, I run into check_aesthetics() errors when I try to use the multi-row axis labels with facet_wrap().
Example Data:
library(data.table)
library(dplyr)
library(ggplot2)
df1 <- data.frame(matrix(ncol = 3, nrow = 12))
colnames(df1)[1:3] <- c("Date", "Group", "Value")
df1$Date <- rep(seq.Date(as.Date("2020-03-14"),as.Date("2020-08-20"),"1 month"),2)
df1$Group <- sort(rep(c("A","B"),6))
df1$Value <- rnorm(12,50,10)
df1 <- df1 %>%
mutate(Month = month(Date),
Year = year(Date),
date = zoo::as.yearmon(paste(Year, Month), "%Y %m"))
df2 <- data.frame(matrix(ncol = 3, nrow = 12))
colnames(df2)[1:3] <- c("Date", "Group", "Value")
df2$Date <- rep(seq.Date(as.Date("2021-03-14"),as.Date("2021-08-20"),"1 month"),2)
df2$Group <- sort(rep(c("A","B"),6))
df2$Value <- rnorm(12,50,10)
df2 <- df2 %>%
mutate(Month = month(Date),
Year = year(Date),
date = zoo::as.yearmon(paste(Year, Month), "%Y %m"))
df3 <- rbind(df1,df2)
cols <- c("A" = "#ca0020", "B" = "#0571b0")
Figure without facet_wrap() showing the multi-row x-axis
ggplot(data = df3, aes(x = factor(date), y = Value, color = Group, group = paste(Year,Group))) +
geom_line() +
geom_point(size = 3, aes(fill = Group), color = "black", shape = 21) +
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
scale_x_discrete(labels=substr(df3$date,1,3))+
labs(x = "") +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 14, color = "black"),
legend.title = element_blank(),
legend.direction = "horizontal",
legend.margin = margin(),
legend.background = element_blank(),
legend.position = c(0.1,0.93),
panel.border = element_blank()) +
guides(fill = guide_legend(nrow = 2)) +
coord_cartesian(clip = 'off', ylim = c(0, 100)) +
annotation_custom(grid::rectGrob(gp = grid::gpar(fill = NA))) +
annotate(geom = "text", x = c(3.5,9.5), y = -15, label = unique(df3$Year), size = 6) +
annotate('rect',
xmin = 6.35,
xmax = 6.65,
ymin = -10, ymax = 0, fill = 'white') +
annotate('segment',
x = c(6.35, 6.65),
xend = c(6.35, 6.65), y = -10, yend = 0)
Now when I try to add the facet_wrap()...
ggplot(data = df3, aes(x = factor(date), y = Value, color = Group, group = paste(Year,Group))) +
geom_line() +
geom_point(size = 3, aes(fill = Group), color = "black", shape = 21) +
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
scale_x_discrete(labels=substr(df3$date,1,3))+
labs(x = "") +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 14, color = "black"),
legend.title = element_blank(),
legend.direction = "horizontal",
legend.margin = margin(),
legend.background = element_blank(),
legend.position = c(0.1,0.93),
panel.border = element_blank()) +
guides(fill = guide_legend(nrow = 2)) +
coord_cartesian(clip = 'off', ylim = c(0, 100)) +
annotation_custom(grid::rectGrob(gp = grid::gpar(fill = NA))) +
annotate(geom = "text", x = c(3.5,9.5), y = -15, label = unique(df3$Year), size = 6) +
annotate('rect',
xmin = 6.35,
xmax = 6.65,
ymin = -10, ymax = 0, fill = 'white') +
annotate('segment',
x = c(6.35, 6.65),
xend = c(6.35, 6.65), y = -10, yend = 0) +
facet_wrap(~Group)
...it throws the error Error in `check_aesthetics()`: ! Aesthetics must be either length 1 or the same as the data (4): label.
The error resides within annotate(geom = "text", x = c(3.5,9.5), y = -15, label = unique(df3$Year), size = 6) + but I can't figure out how to fix it. I have tried changing the label = and the x = but no luck. The ideal figure would have two plots, each with multi-row x-axis labels where, similar to the example figure above, the top row is month and the second row is year. Any thoughts on how to achieve this?
If you don't mind moving the year value to the strip you could use ggh4x package.
library(dplyr)
library(ggplot2)
library(lubridate)
library(ggh4x)
ggplot(data = df3, aes(x = factor(date), y = Value, color = Group, group = paste(Year,Group))) +
geom_line() +
geom_point(size = 3, aes(fill = Group), color = "black", shape = 21) +
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
scale_x_discrete(labels=substr(df3$date,1,3))+
labs(x = NULL) +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 14, color = "black"),
legend.title = element_blank(),
legend.direction = "horizontal",
legend.margin = margin(),
legend.background = element_blank(),
legend.position = c(0.1,0.90),
panel.border = element_blank()) +
guides(fill = guide_legend(nrow = 2)) +
coord_cartesian(clip = 'off', ylim = c(0, 100)) +
facet_nested(~Group + Year, scales = "free_x")
Created on 2022-10-12 with reprex v2.0.2
One kind of hacky way to do this is to just make two text annotations
ggplot(data = df3, aes(x = factor(date), y = Value, color = Group, group = paste(Year,Group))) +
geom_line() +
geom_point(size = 3, aes(fill = Group), color = "black", shape = 21) +
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
scale_x_discrete(labels=substr(df3$date,1,3))+
labs(x = "") +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 14, color = "black"),
legend.title = element_blank(),
legend.direction = "horizontal",
legend.margin = margin(),
legend.background = element_blank(),
legend.position = c(0.1,0.93),
panel.border = element_blank()) +
guides(fill = guide_legend(nrow = 2)) +
coord_cartesian(clip = 'off', ylim = c(0, 100)) +
annotation_custom(grid::rectGrob(gp = grid::gpar(fill = NA))) +
annotate(geom = "text", x = c(3.5), y = -15, label = 2020, size = 6) +
annotate(geom = "text", x = c(9.5), y = -15, label = 2021, size = 6) +
annotate('rect',
xmin = 6.35,
xmax = 6.65,
ymin = -10, ymax = 0, fill = 'white') +
annotate('segment',
x = c(6.35, 6.65),
xend = c(6.35, 6.65), y = -10, yend = 0) +
facet_wrap(~Group)

ggplot box plot with data points: how to control legend appearance?

I tried various options, but I cannot find a way to achieve custom legend appearance (unless I export the figure to power point and edit it there...). I would like the legend to look like in the image below and wonder if that is at all possible:
I do not wish to make any changes in the figure itself:
Here is my sample data and code:
df = data.frame(sex = c(1,1,1,1,1, 2,2,2,2,2),
age_cat = c(1,1,1, 2,2,2, 1,1,1, 2),
score_type = c(1,2, 1,2, 1,2, 1,2, 1,2),
score = c(25,28,18,20,30, 37,40,35,43,45))
df$sex <- factor((df$sex))
df$age_cat <- factor((df$age_cat))
df$score_type <- factor((df$score_type))
windows(width=7, height=7)
library(ggplot2)
df %>%
ggplot( aes(x=score_type, y=score)) +
geom_boxplot(aes(color=sex),outlier.shape = NA, size=1.5, show.legend=T) +
geom_point(aes(color=sex, shape = age_cat, group = sex),
position=position_jitterdodge(dodge.width=0.9), size=3, show.legend=F) +
scale_color_manual(values=c("#0072B2", "#CC79A7"), name="",
labels=c("Male", "Female")) +
scale_shape_manual(name="", labels=c('Younger', 'Older'),
values=c(16, 17)) +
theme_bw()+
theme(panel.border = element_blank(), axis.ticks = element_blank(),
legend.position=c(0.9, 0.65), legend.text=element_text(size=11),
legend.title=element_text(size=11.5),
panel.grid.major.x = element_blank() ,
plot.title = element_text(size=11, face = "bold"),
axis.title=element_text(size=13),
axis.text.y = element_text(size=11),
axis.text.x = element_text(size=11),
plot.margin = unit(c(0.5,0.2,0,0.2), "cm")) +
labs(title= "", x = "",y = "Score") +
scale_y_continuous(breaks=c(0, 20, 40, 60, 80, 100),
labels=c('0', '20', '40', '60', '80', '100')) +
expand_limits(x=5, y=70) +
scale_x_discrete(labels = c("A", "B")) +
coord_cartesian(clip = "off")
You could achieve your desired result by
dropping show.legend=FALSE from geom_point
Overriding the shapes to be displayed in the legend using guides(shape = guide_legend(override.aes = list(shape = c(1, 2))))
library(ggplot2)
ggplot(df, aes(x = score_type, y = score)) +
geom_boxplot(aes(color = sex), outlier.shape = NA, size = 1.5) +
geom_point(aes(color = sex, shape = age_cat, group = sex),
position = position_jitterdodge(dodge.width = 0.9), size = 3
) +
scale_color_manual(
values = c("#0072B2", "#CC79A7"), name = "",
labels = c("Male", "Female")
) +
scale_shape_manual(
name = "", labels = c("Younger", "Older"),
values = c(16, 17)
) +
theme_bw() +
theme(
panel.border = element_blank(), axis.ticks = element_blank(),
legend.position = c(0.9, 0.65), legend.text = element_text(size = 11),
legend.title = element_text(size = 11.5),
panel.grid.major.x = element_blank(),
plot.title = element_text(size = 11, face = "bold"),
axis.title = element_text(size = 13),
axis.text.y = element_text(size = 11),
axis.text.x = element_text(size = 11),
plot.margin = unit(c(0.5, 0.2, 0, 0.2), "cm")
) +
labs(title = "", x = "", y = "Score") +
scale_y_continuous(
breaks = c(0, 20, 40, 60, 80, 100),
labels = c("0", "20", "40", "60", "80", "100")
) +
expand_limits(x = 5, y = 70) +
scale_x_discrete(labels = c("A", "B")) +
coord_cartesian(clip = "off") +
guides(shape = guide_legend(override.aes = list(shape = c(1, 2))))

Changing x axis on my plot to fit in one more value: xlim, scale_x_continuous not working

I created a cleveland dot plot for my data, but it stops a bit shorter than the last data point.
I would like it to end on 7000. I tried to use xlim(1000,7000) and scale_x_continuous(breaks = seq(1000, 7000, by = 1000) but it doesnt work. My code:
ggplot(tidydf, aes(Genome_size, `Trio_number`, color = Group)) +
geom_point() + geom_line(aes(group = Trio_number), color = 'grey30') +
scale_y_continuous(breaks = seq(0, 20, by = 1)) + scale_x_continuous(breaks = seq(1000,
7000, by = 1000) +
ylab("Trio number") + xlab("Genome size (kb)") + theme_dotplot + theme(legend.position =
"bottom") + scale_color_brewer(palette = "Set2") + theme(legend.title=element_blank()) +
guides(colour = guide_legend(override.aes = list(size=4))) +
theme(legend.key=element_rect(fill='grey96')) +
theme(plot.background = element_rect(fill = 'grey96')) + theme(legend.title =
element_text(size=10)) + theme(text=element_text(size=12, family="Gujarati Sangam MN"))
+ theme(axis.title.x = element_text(vjust = 0, size = 12), axis.title.y =
element_text(vjust = 2, size = 12)) + theme(axis.text = element_text(color = "black",
size = 9))
Reproducible data:
library(ggplot2)
library(scales)
set.seed(8675309)
tidydf <- data.frame(
Genome_size = sample(1000:7000, 30, replace = T),
Trio_number = sample(1:20, 30, replace = T),
Group = sample(c('Free-living', 'Gut', 'Pathogen'), 30, replace = T)
)
p <-
ggplot(tidydf, aes(Genome_size, `Trio_number`, color = Group)) +
geom_point() +
scale_y_continuous(breaks = seq(0, 20, by = 1)) +
ylab("Trio number") + xlab("Genome size (kb)") +
theme_light() +
scale_x_continuous(labels = comma) +
scale_color_brewer(palette = "Accent") +
guides(colour = guide_legend(override.aes = list(size=4))) +
theme(
legend.position = "bottom",
legend.key=element_rect(fill='gray96'),
plot.background = element_rect(fill = 'gray96'),
legend.title =element_text(size=10),
text=element_text(size=12),
axis.title.x = element_text(vjust = 0, size = 11),
axis.title.y = element_text(vjust = 2, size = 11),
axis.text = element_text(color = "black", size = 9),
# to make the theme look more similar to OP example
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)
p
Thanks!
I think it would work by adding both limits = c(1000, 7000) and breaks = seq(1000, 7000, by = 1000) inside the scale_x_continuous call:
library(ggplot2)
library(scales)
set.seed(8675309)
tidydf <- data.frame(
Genome_size = sample(1200:6800, 30, replace = T),
Trio_number = sample(1:20, 30, replace = T),
Group = sample(c('Free-living', 'Gut', 'Pathogen'), 30, replace = T)
)
ggplot(tidydf, aes(Genome_size, `Trio_number`, color = Group)) +
geom_point() +
geom_line(aes(group = Trio_number), color = 'grey30') +
scale_y_continuous(breaks = seq(0, 20, by = 1)) +
ylab("Trio number") + xlab("Genome size (kb)") +
theme_light() +
scale_x_continuous(labels = comma,
limits = c(1000, 7000),
breaks = seq(1000, 7000, by = 1000)) +
scale_color_brewer(palette = "Accent") +
guides(colour = guide_legend(override.aes = list(size=4))) +
theme(
legend.position = "bottom",
legend.key=element_rect(fill='gray96'),
plot.background = element_rect(fill = 'gray96'),
legend.title =element_text(size=10),
text=element_text(size=12),
axis.title.x = element_text(vjust = 0, size = 11),
axis.title.y = element_text(vjust = 2, size = 11),
axis.text = element_text(color = "black", size = 9),
# to make the theme look more similar to OP example
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)
Created on 2021-03-22 by the reprex package (v1.0.0)

How to properly format percentage plot axis labels and bars in ggplot2

I've got a dataframe I imported from SPSS into R, and I'm having trouble properly formatting the y axis in a ggplot2 percentage bar chart.
I need to constrain the axis range to a smaller amount and also lengthen those bars. This is what I keep getting:
Here's the code for the above visualization:
#import packages
library(foreign)
library(ggthemes)
library(stringr)
library(ggplot2)
library(scales)
#read in data
WBGC <- read.spss("2019.07.14_Cleaned.Data.sav", use.value.label=TRUE, to.data.frame=TRUE)
#define member/non-member datasets
WBGC_members <- subset(WBGC, Freq.Of.Attendance == 'Once a month' | Freq.Of.Attendance == 'A few times a month' | Freq.Of.Attendance == 'Once or twice a week' | Freq.Of.Attendance == '3-5 days a week')
#visualization of race
student_race <- ggplot(data = WBGC_members, aes(x = Race, fill = Gender))
+ theme_hc()
+ geom_bar(colour = "black", stat = "count", aes(y = prop.table(stat(count))), position = position_dodge(), size = 0.5)
+ labs(title = "Student Race", y = "Frequency")
+ scale_y_continuous(labels = percent)
+ geom_label(data = WBGC_members, stat = 'count', aes(label = scales::percent(prop.table(stat(count))), vjust = -0.4, fontface = 'bold'), size = 6, position = position_dodge(0.9), alpha = 1.0, show.legend = FALSE)
+ theme(
plot.title = element_text(size = 16, face = 'bold', family = '', color = 'black', hjust = 0.5, lineheight = 1.2),
axis.title.x = element_blank(),
axis.text.x = element_text(size = 12, angle = 45, vjust = 0.5),
axis.title.y = element_text(size = 14, margin = margin(t = 0, r = 8, b = 0, l = 0)),
axis.text.y = element_text(size = 12),
legend.title = element_text(size = 14, color = "black", face="bold", hjust = 1, lineheight = 4),
legend.text = element_text(size = 13),
legend.position = 'right',
legend.box.background = element_rect(colour = 'black')
)
student_race
Since it looks like the labels are doing OK, I added scales::percent to the aes y= argument in geom_bar and had to delete the scale_y_continuous function. I wound up with this:
Any help is much appreciated. Thanks!
Fixed by adding y = prop.table(stat(count)) to the geom_label function call.
Here's the result:
And final code for reference:
student_race <- ggplot(data = WBGC_members, aes(x = Race, fill = Gender)) +
theme_hc()+
geom_bar(colour = "black", stat = "count", aes(y = prop.table(stat(count))), position = position_dodge(), size = 0.5) +
geom_label(data = WBGC_members, stat = 'count', aes(label = scales::percent(prop.table(stat(count))), y = prop.table(stat(count)), vjust = -0.4, fontface = 'bold'), size = 6, position = position_dodge(0.9), alpha = 1.0, show.legend = FALSE) +
labs(title = "Student Race", y = "Frequency") +
scale_y_continuous(labels = scales::percent, limits = c(0,0.2)) +
theme(plot.title = element_text(size = 16, face = 'bold', family = '', color = 'black', hjust = 0.5, lineheight = 1.2),
axis.title.x = element_blank(),
axis.text.x = element_text(size = 12, angle = 45, vjust = 0.5),
axis.title.y = element_text(size = 14, margin = margin(t = 0, r = 8, b = 0, l = 0)),
axis.text.y = element_text(size = 12),
legend.title = element_text(size = 14, color = "black", face="bold", hjust = 1, lineheight = 4),
legend.text = element_text(size = 13),
legend.position = 'right',
legend.box.background = element_rect(colour = 'black')
)
student_race

Using ggplot2; How to get position_dodge() to work with this example?

Background
I took the data from a Stephen Few Example and wanted to add labels to each of the bars to pull the legend from the side of the graphic.
The code in the "Hack Graphic" section got me there because I couldn't get the position_dodge() to work with the text labels.
Load Data
library(tidyverse)
library(forcats)
### Build data from his table
candidates <- tibble::tibble(`Rating Areas` = c("Experience",
"Communication", "Friendliness", "Subject matter knowledge", "Presentation",
"Education"), `Karen Fortou` = c(4,3.5, 4, 4, 3, 3.5), `Mike Rafun` = c(4.5,
2, 2, 5, 1.5, 4.5), `Jack Nymbul` = c(2.5, 5, 4.5, 2.5, 2.75, 2)) %>%
gather("Candidates", "Score", -`Rating Areas`)
# The totals for each candidate
totals <- candidates %>% group_by(Candidates) %>% summarise(Score =
sum(Score))
Hack Graphic
Notice how I used manually created x-axis values (x = c(seq(.6,1.35, by = .15), seq(1.6,2.35, by = .15), seq(2.6,3.35, by = .15))) to place the labels instead of using position = position_dodge() as described in this post.
candidates %>%
ggplot(aes(x = fct_reorder(Candidates, Score), y = Score)) +
geom_col(data = totals, alpha = .45) +
geom_col(aes(fill = `Rating Areas`), position = position_dodge(.9), color = "black",
show.legend = FALSE) +
geom_text(label = rep(c("Experience", "Communication", "Friendliness",
"Subject matter knowledge", "Presentation", "Education"),3),
x = c(seq(.6,1.35, by = .15), seq(1.6,2.35, by = .15),
seq(2.6,3.35, by = .15)), y = 5.1, angle = 90, color = "black",
hjust = "left", size = 4, fontface = "bold") +
scale_fill_brewer(type = "qual") +
scale_y_continuous(breaks = seq(0, 25, by = 2)) +
theme_bw() +
labs(x = "\nCandidates", y = "Rating Score") +
theme(axis.text.x = element_text(size = 14, color = "black"), legend.text = element_text(size = 14),
legend.title = element_text(size = 15), axis.title = element_text(size = 15))
Graphic Code that doesn't work
When I follow the example from the previous Stack answer using geom_text(aes(label =Rating Areas), position = position_dodge(width = 0.9), angle = 90, color = "black", hjust = "left", size = 4, fontface = "bold") it does not spread the labels out ever each bar.
I must be missing something obvious. Please help with how to get position_dodge() to work with this example?
candidates %>%
ggplot(aes(x = fct_reorder(Candidates, Score), y = Score)) +
geom_col(data = totals, alpha = .45) +
geom_col(aes(fill = `Rating Areas`), position = position_dodge(.9), color = "black", show.legend = FALSE) +
geom_text(aes(label = `Rating Areas`), position = position_dodge(width = 0.9), angle = 90, color = "black", hjust = "left", size = 4, fontface = "bold") +
scale_fill_brewer(type = "qual") +
scale_y_continuous(breaks = seq(0, 25, by = 2)) +
theme_bw() +
labs(x = "\nCandidates", y = "Rating Score") +
theme(axis.text.x = element_text(size = 14, color = "black"), legend.text = element_text(size = 14), legend.title = element_text(size = 15), axis.title = element_text(size = 15))
I think you need to have the same mapping for both geom_col and geom_text. You can add fill = Rating Areas to the aesthetics of geom_text. You will get a warning though.
candidates %>%
ggplot(aes(x = fct_reorder(Candidates, Score), y = Score)) +
geom_col(data = totals, alpha = .45) +
geom_col(aes(fill = `Rating Areas`), position = position_dodge(.9), color = "black", show.legend = FALSE) +
geom_text(aes(fill = `Rating Areas`, label = `Rating Areas`), position = position_dodge(width = 0.9), angle = 90, color = "black", hjust = "left", size = 4, fontface = "bold") +
scale_fill_brewer(type = "qual") +
scale_y_continuous(breaks = seq(0, 25, by = 2)) +
theme_bw() +
labs(x = "\nCandidates", y = "Rating Score") +
theme(axis.text.x = element_text(size = 14, color = "black"), legend.text = element_text(size = 14), legend.title = element_text(size = 15), axis.title = element_text(size = 15))
Edit: Here's a way to do it without the warning:
candidates %>%
ggplot(aes(x = fct_reorder(Candidates, Score), y = Score, fill = `Rating Areas`)) +
geom_col(data = totals, aes(x = fct_reorder(Candidates, Score), y = Score), alpha = .45, inherit.aes = FALSE) +
geom_col(position = position_dodge(.9), color = "black", show.legend = FALSE) +
geom_text(aes(label = `Rating Areas`), position = position_dodge(width = 0.9), angle = 90, color = "black", hjust = "left", size = 4, fontface = "bold") +
scale_fill_brewer(type = "qual") +
scale_y_continuous(breaks = seq(0, 25, by = 2)) +
theme_bw() +
labs(x = "\nCandidates", y = "Rating Score") +
theme(axis.text.x = element_text(size = 14, color = "black"), legend.text = element_text(size = 14), legend.title = element_text(size = 15), axis.title = element_text(size = 15))

Resources