假設我使用以下代碼創建了一個 ggplot barplot:
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
#pelacolset
ggplot(mtcars,
#color by which to fill
aes(fill=gear,
#y axis
y=wt,
#x axis
x=carb))
#title and subtitle
#barplot
geom_bar(position="fill", stat="identity",width=.8)
coord_flip()
#rotate x axis labels 90 degrees
theme(axis.text.x = element_text(angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
情節是這樣的:

現在我想使用 carb_labelright 列在條形圖的右側添加資料。它應該是這樣的:

如何才能做到這一點?
uj5u.com熱心網友回復:
我發現用geom_text(您需要一個資料框)或annotate(geom = "text",...). 使用 annotate 通常更安全,因為geom_text喜歡為每一行創建一個標簽(當您使用精心準備的資料框進行注釋時,這很好)。
library(tidyverse)
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
ggplot(mtcars)
# use geom_col, a convenience wrapper for geom_bar(stat = "identity")
geom_col(aes(fill=gear, y=wt, x=carb),
position="fill", width=.8)
# you have to turn clipping off
coord_flip(clip = "off")
annotate(geom = "text", x = unique(mtcars$carb),
label = unique(mtcars$carb_labelright),
y = 1, hjust = 0)
# you need to increase the legend's margin and make it "transparent"
# otherwise you will cover some labels.
theme(legend.margin = margin(l = 1, unit = "inch"),
legend.background = element_blank())

由reprex 包(v2.0.1)于 2021 年 10 月 26 日創建
uj5u.com熱心網友回復:
我還遇到了不支持二級刻度的離散軸的問題(請參閱ggplot2 repo 上的相關問題)。我通過自己撰寫手動指南解決了這個問題,該指南確實允許我制作具有離散比例的輔助軸。在下面的代碼中,我們ggh4x::guide_axis_manual()結合使用 rlang/purrr lambda 函式來格式化標簽。(免責宣告:我是 ggh4x 的作者)。
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.1
mtcars$carb<-as.character(mtcars$carb)
mtcars$gear<-as.character(mtcars$gear)
mtcars$carb_labelright<-paste0("label_right",mtcars$carb)
p <- ggplot(mtcars,
aes(fill = gear, y = carb, x = wt))
geom_col(position="fill", width=.8)
p guides(
y.sec = ggh4x::guide_axis_manual(
labels = ~ paste0("label_right_", .x)
)
)

或者,您也可以直接將標簽作為字符向量。
p guides(
y.sec = ggh4x::guide_axis_manual(
labels = sort(unique(mtcars$carb_labelright))
)
)

由reprex 包(v2.0.1)于 2021 年 10 月 26 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338238.html
