我創建了以下示例資料:
df <- data.frame(list(Category = c("A", "A", "A", "B", "B",
"B", "B", "B", "B", "C", "C", "C", "D", "D", "D","E",
"E", "E"), Axis2 = c(0.34, 0.34, 0.34, 0.22, 0.22, 0.22,
0.29, 0.29, 0.29, 0.53, 0.53, 0.53, 0.67, 0.67, 0.67, 0.42,
0.42, 0.42), Offices = c("Office 1", "Office 2", "Office 3",
"Office 1", "Office 2", "Office 3", "Office 1", "Office 2",
"Office 3", "Office 1", "Office 2", "Office 3", "Office 1",
"Office 2", "Office 3", "Office 1", "Office 2", "Office 3"),
Axis1 = c(0.03, 0.02, 0.04, 0.1, 0.08, 0.07, 0.12, 0.211,
0.18, 0.05, 0.07, 0.08, 0.01, 0.02, 0.03, 0.07, 0.011, 0.012)))
我想Category在 y 軸上繪制列,將Axis1列作為條形圖的 x 軸,將Axis2列作為線圖的 x 軸。條形圖的填充也由Category列決定。然后資料由 分面Offices。
我有以下情節代碼:
ggplot(df) theme_minimal() guides(fill = FALSE)
geom_col(aes(x = Axis1, y = Category, fill = Category))
geom_line(aes(x = Axis2, y = Category), stat = "identity", group = 1)
labs(y = element_blank(), x = "Percentage of Thing 1")
facet_wrap(~Offices, ncol = 3)
scale_x_continuous(labels = scales::percent_format(accuracy = 1),
sec.axis = sec_axis(~./max(data$Compliance),
label=scales::percent))
theme(axis.text.y = element_text(size = 11, color = "black"),
strip.text = element_text(size = 18, color = "black",
face = "bold", margin = margin(c(0.2,0,0.6,0), unit = "in")),
axis.title.x = element_text(size = 12, color = "black",
margin = margin(c(0.2,0,0.1,0), unit = "in")),
panel.grid.major.x = element_line(color = "gray86"),
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank())
我面臨3個主要問題:
- 第二個 x 軸的位置,我希望它位于圖上方的刻面標題下方。
- 第二個 x 軸標簽未顯示
Axis2列中的資料 - 這兩個圖似乎仍在使用主要的 x 軸刻度,因為條形圖被縮小以適應折線圖。我希望它們在共享 y 軸但不共享 x 軸的情況下彼此獨立。

uj5u.com熱心網友回復:
要將條形標簽放置在軸上方,請使用strip.placement= "outside". 要為您的軸獲得正確的比例,您還必須縮放要在輔助比例上繪制的資料。
library(ggplot2)
scale <- max(df$Axis1)
ggplot(df)
theme_minimal()
guides(fill = "none")
geom_col(aes(x = Axis1, y = Category, fill = Category))
geom_line(aes(x = Axis2 * scale, y = Category), stat = "identity", group = 1)
labs(y = element_blank(), x = "Percentage of Thing 1")
facet_wrap(~Offices, ncol = 3)
scale_x_continuous(
labels = scales::percent_format(accuracy = 1),
sec.axis = sec_axis(~ . / scale, label = scales::percent)
)
theme(
axis.text.y = element_text(size = 11, color = "black"),
strip.text = element_text(
size = 18, color = "black",
face = "bold", margin = margin(c(0.2, 0, 0.6, 0), unit = "in")
),
axis.title.x = element_text(
size = 12, color = "black",
margin = margin(c(0.2, 0, 0.1, 0), unit = "in")
),
panel.grid.major.x = element_line(color = "gray86"),
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank(),
strip.placement = "outside"
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474415.html
