Using the packages ggplot2, dplyr and scales, I make the code the following plot
grafico_4 <- ggplot()
ggtitle("Grafico variado")
theme(plot.title = element_text(size = 10))
theme(panel.background = element_rect(fill='white', colour='white'))
theme( axis.line = element_line(colour = "black", size = 0.5))
scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))
scale_x_discrete(limits = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", ""))
geom_hline(yintercept = 5, linetype = "dotted")
ylab("")
But why do I get a line between "uno" and "dos" and not between "cinco" and "siete", "siete" and "nueve", and after "nueve"? How do I get the lines to appear?
CodePudding user response:
The limits argument of scale_x_discrete
is a place to put possible values of the scale. But it can't show the same value more than once.
So the hackiest possible solution I could think of would be to use different blank strings:
scale_x_discrete(limits = c("uno", "", "tres", " ", "cinco", " ", "siete", " ", "nueve"))
This is a terrible solution but I felt compelled to share.
EDIT: Here's a different approach that I think relies on (in my opinion) more typical ggplot2 syntax. One issue I didn't expect is that ggplot2 doesn't seem to want to print the x axis, even if its breaks and limits are specified, until there is a geom that exists in "x-space" -- ie geom_hline won't trigger it, but in this case an invisible point with an x value will.
I think it's more natural to use continuous axes here. In this case I make the labels for the x axis alternate between the text values and blanks using a trick I found here: https://stackoverflow.com/a/25961969/6851825
It turns c("uno", "tres")
into c("uno", "", "tres", "")
.
nums <- c("uno", "tres", "cinco", "siete", "nueve")
ggplot()
ggtitle("Grafico variado")
theme_classic()
theme(plot.title = element_text(size = 10))
scale_y_continuous(breaks = 1:10, name = NULL)
scale_x_continuous(breaks = 1:10, name = NULL,
labels = c(rbind(nums, "")))
coord_cartesian(xlim = c(0,11), ylim = c(0,10), expand = 0)
geom_hline(yintercept = 5, linetype = "dotted")
annotate("point", x = 5, y = 0, alpha = 0)
CodePudding user response:
What you're describing are not limits; they are x-axis labels. If you encode the limits and labels as such, you get the expected output.
library(ggplot2)
ggplot()
ggtitle("Grafico variado")
theme(plot.title = element_text(size = 10))
theme(panel.background = element_rect(fill='white', colour='white'))
theme( axis.line = element_line(colour = "black", size = 0.5))
scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))
scale_x_discrete(
limits = factor(1:10),
labels = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", "")
)
geom_hline(yintercept = 5, linetype = "dotted")
ylab("")
Created on 2021-10-24 by the reprex package (v2.0.1)