![](/img/trans.png)
[英]Create a legend, change Y-axis for a ggplot2 plot that has a geom_col and 4 geom_line plots
[英]Plot geom_col and geom_line with different x-axis percentage scales on the same graph in r
我創建了以下示例數據:
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)))
我想在 y 軸上繪制Category
列, 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個主要問題:
Axis2
列中的數據要將條形標簽放置在軸上方,請使用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"
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.