Suppose I create a ggplot barplot with this code:
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
#pelacolset
ggplot(mtcars,
#color by which to fill
aes(fill=gear,
#y axis
y=wt,
#x axis
x=carb))
#title and subtitle
#barplot
geom_bar(position="fill", stat="identity",width=.8)
coord_flip()
#rotate x axis labels 90 degrees
theme(axis.text.x = element_text(angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Now I would like to use the column carb_labelright to add the data on the right side of the bar plot. It should look like this:
How can this be done?
CodePudding user response:
I find easiest to annotate with geom_text
(you'll need a data frame) or with annotate(geom = "text",...)
. Using annotate is usually safer, as geom_text
likes to create a label for each row (which is fine when you use carefully prepared data frames for annotation).
library(tidyverse)
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
ggplot(mtcars)
# use geom_col, a convenience wrapper for geom_bar(stat = "identity")
geom_col(aes(fill=gear, y=wt, x=carb),
position="fill", width=.8)
# you have to turn clipping off
coord_flip(clip = "off")
annotate(geom = "text", x = unique(mtcars$carb),
label = unique(mtcars$carb_labelright),
y = 1, hjust = 0)
# you need to increase the legend's margin and make it "transparent"
# otherwise you will cover some labels.
theme(legend.margin = margin(l = 1, unit = "inch"),
legend.background = element_blank())
Created on 2021-10-26 by the reprex package (v2.0.1)
CodePudding user response:
I also ran into the problem of discrete axes not supporting secondary scales (see related issue on the ggplot2 repo). I solved it by writing a manual guide myself that does allow me to make secondary axes with discrete scales. In the code below, we use ggh4x::guide_axis_manual()
in combination with an rlang/purrr lambda function to format the labels. (Disclaimer: I'm the author of ggh4x).
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.1
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
p <- ggplot(mtcars,
aes(fill = gear, y = carb, x = wt))
geom_col(position="fill", width=.8)
p guides(
y.sec = ggh4x::guide_axis_manual(
labels = ~ paste0("label_right_", .x)
)
)
Alternatively, you can give the labels as a character vector directly too.
p guides(
y.sec = ggh4x::guide_axis_manual(
labels = sort(unique(mtcars$carb_labelright))
)
)
Created on 2021-10-26 by the reprex package (v2.0.1)