I have the stacked bar chart below and I would like to know if it is possible to set a max limit of characters displayed in the values of the y-axis, for example 4, and then add a "." at the point that the characters stop. For example "subcompact" should become "subc."
g <- ggplot(mpg, aes(class))
g+geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
coord_flip() +
theme(legend.position = "top")
如果您不想更改源数据,也可以用ggplot代码进行替换-这是略有不同的regex解决方案@AndreElrico的
g <- ggplot(mpg, aes(sub(class,pattern = "(\\w{4}).*",replacement = "\\1.")))
change your variable into your desired variable before using it.
mpg$class <- sub("(?<=^.{4}).*",".", mpg$class, perl = T)
You can use regex to archive this.
You can adjust the labels with scale_x_discrete
, which means no editing of the dataset is done.
g+geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
scale_x_discrete(
labels = function(x) {
is_long <- nchar(x) > 4
x[is_long] <- paste0(substr(x[is_long], 1, 4), ".")
x
}
) +
coord_flip() +
theme(legend.position = "top")
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.