我想我的問題對于非常了解 ggplot 的人來說非常簡單,但我花了很多時間嘗試不同的方式。我想畫一條通過 y 軸的水平線來分隔使用geom_col. 例如,我想畫一條將肉條與玉米分開的水平線。這是我的代碼、示例資料和我想要制作的圖形的設計。
library(tidyverse)
library(ggplot2)
# sample data
Food = c("meat", "meat", "meat", "meat", "wheat","wheat","wheat", "wheat", "maize","maize","maize","maize")
Subgroup = c("Male", "Female", "Urban", "Rural", "Male", "Female", "Urban", "Rural", "Male", "Female","Urban", "Rural")
mean = c(8.66, 10.45, 9.88, 7.32, 21.04, 19.65, 20.26, 20.87, 51.06 , 44.51, 47.60, 48.40)
df <- data.frame(Food, Subgroup, mean)
#Color code
colorPanel = c('#083c5d','#2d004b','#106d8e','#7d103d')
# Plot
Plot_FBGDS <- ggplot(df, aes(x = Food, y = mean, fill = Subgroup))
geom_col(stat = "identity", position = position_dodge(-0.9), width = 0.82)
scale_y_continuous(breaks = c(0,20, 40, 60,80), expand = c(0,0),
limits = c(0,100),
labels = function(x) paste0(x, "%"))
coord_flip()
scale_fill_manual(values = colorPanel)
labs( x= " ",
y = " ")
uj5u.com熱心網友回復:
試試這個,使用geom_vline手動指定xintercept的 .
# Plot
ggplot(df, aes(x = Food, y = mean, fill = Subgroup))
geom_col(stat = "identity", position = position_dodge(-0.9), width = 0.82)
scale_y_continuous(breaks = c(0,20, 40, 60,80), expand = c(0,0),
limits = c(0,100),
labels = function(x) paste0(x, "%"))
geom_vline(xintercept = c(0.5, 1.5, 2.5, 3.5))
coord_flip()
scale_fill_manual(values = colorPanel)
labs( x= " ",
y = " ")
請注意,geom_vline通常會產生一條垂直線,但既然你有coord_flip它就變成水平的。如果沒有coord_flip,您將使用geom_hline并設定yintercept引數。
另外,如果我可以建議使用另一種方法來可視化它facet_wrap,我會說下面的選項看起來好多了,您可以使用以下strip_屬性設定構面的樣式plot_theme
# Plot
ggplot(df, aes(x = Subgroup, y = mean, fill = Subgroup))
geom_col(stat = "identity", position = position_dodge(-0.9), width = 0.82)
scale_y_continuous(breaks = c(0,20, 40, 60,80), expand = c(0,0),
limits = c(0,100),
labels = function(x) paste0(x, "%"))
coord_flip()
scale_fill_manual(values = colorPanel)
facet_wrap(~Food, ncol=1)
labs( x= " ",
y = " ")
theme(
legend.position = "none"
)
uj5u.com熱心網友回復:
我將建立已經從@geoff 發布
請注意,我必須將其Subgroup作為列包含在linesdata資料框中。避免這樣做的方法是指定fill=內部而不是全域的美學geom_col......但它也可以這樣作業。
geom_hline和vline總是clip的原因
有趣的是,您會注意到,即使yend=Inf,這條線也不會在正方向上超出面板區域!我不知道這是這樣作業的,但它似乎Inf是專門設計用來夾到面板區域的。我很確定geom_vline()并且geom_hline()正在使用引擎蓋下的Inf值。-Inf如果我將值更改為y=-Infinside geom_segment(),您會看到它的擴展方式與指定數字不同:
ggplot(df, aes(x = Food, y = mean, fill = Subgroup))
geom_col(position = position_dodge(-0.9), width = 0.82)
scale_y_continuous(breaks = c(0,20, 40, 60,80), expand = c(0,0),
limits = c(0,100),
labels = function(x) paste0(x, "%"))
coord_flip(clip="off")
geom_segment(
data=linesdata, y=-Inf, yend=Inf,
aes(x=xvals, xend=xvals)
)
scale_fill_manual(values = colorPanel)
labs( x= " ",
y = " ")

這里唯一的問題是,您必須通過反復試驗找到合適的起始 y 值。我發現 -5 做得很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417431.html
標籤:
下一篇:將日期轉換為所需格式
