I need to display the labels of the x-axis both above and below my ggplot, aligned with the corresponding data points. I have already created a ggplot with the necessary data and aesthetics, but I am struggling to duplicated the x-axis because it is a categorical variable.
Since with scale_x_discrete is not possible to duplicate an axis, I tried to use scale_x_continuous(), splitting the categorical variable with breaks and defining a character vector as labels.
‘plot’ is my ggplot with data and aesthetics.
The variable ‘birds$species_name’ is a factor containing the names of bird species.
plot + scale_x_continuous(breaks = 1:length(birds$species_name),
labels = as.character(birds$species_name),
sec.axis = dup_axis())
As suggested by a previous question online, I also tried this code.
plot + scale_x_continuous(breaks = 1:length(birds$species_name),
labels = as.character(birds$species_name),
sec_axis(~.,
breaks = 1:length(birds$species_name),
labels = as.character(birds$species_name)))
I would have expected the code to successfully duplicate the x-axis in my plot, but always returns me the error “Discrete value supplied to continuous scale”.
Any suggestion would be highly appreciated, thanks in advance!
Francesca Frisoni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3