![](/img/trans.png)
[英]Set left and right limit ranges simultaneously for dual y-axis plot using ggplot2
[英]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?
我下面有堆積的條形圖,我想知道是否可以設置在y軸值中顯示的最大字符限制,例如4,然后添加“。”。 在字符停止的時候。 例如,“超小型”應變為“ 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.")))
在使用之前,將變量更改為所需的變量。
mpg$class <- sub("(?<=^.{4}).*",".", mpg$class, perl = T)
您可以使用正則表達式對此進行存檔。
您可以使用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.