install.packages("ggplot2")
library(ggplot2)
vector1 <- c(1, 4, 5, 6, 2, 4, 5, 8)
vector2 <- c(1, 2, 3, 4, 5, 6, 7, 8)
dataframe <- data.frame(vector1, vector2)
dataframe$vector2 <- as.factor(dataframe$vector2)
plot <- ggplot(dataframe, aes(vector2, vector1))
plot +geom_bar(stat = "identity")
I would like to make a text box somewhere in the bar chart window that shows values of 1-8 corresponding to levels of a factor. If I give the levels character-based names, it clutters the x-axis, and I don't want that. So I figured a legend that corresponds numbers to the levels would be great alternative. eg Ideally, each level of a factor is descending as a row, like a legend.
1 - slippery roads 2 - dry roads 3 - something creative
etc.
Ok here is another approach. There might be easier ones.
We use the guide for fill, remove the legend keys and overlay a second set of bars.
ggplot() + geom_col(data = dataframe, aes(vector2, vector1, fill = vector2)) +
geom_col(data = dataframe, mapping = aes(vector2, vector1)) +
scale_fill_discrete(name = "", labels = paste0(1:8, " roads")) +
theme(legend.position = c(.3, .8),
legend.key = element_blank(),
legend.background = element_blank()) +
guides(fill=guide_legend(override.aes=list(fill = NA),
keywidth = 0, keyheight = 0, nrow = 2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.