[英]How to set a max limit to the characters of the values that are displayed on the y-axis of a plot, through the ggplot code?
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 "." 我下面有堆积的条形图,我想知道是否可以设置在y轴值中显示的最大字符限制,例如4,然后添加“。”。 at the point that the characters stop.
在字符停止的时候。 For example "subcompact" should become "subc."
例如,“超小型”应变为“ 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. 您可以使用
scale_x_discrete
调整标签,这意味着不对数据集进行任何编辑。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.