簡體   English   中英

ggplot在X軸下方添加跟蹤顏色

[英]ggplot Adding Tracking Colors Below X-Axis

我想在x軸下方添加一條線,其顏色取決於未繪制的因子。

在此示例中,我正在創建箱形圖,並希望添加一條線來指示另一個變量。

以汽車數據集為例,然后物理上嘗試做的事情:

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
geom_boxplot()

在此處輸入圖片說明

我的想法是創建一個條形圖,一個柱形圖或geom_tile圖,然后將其布置在箱線圖下方。 這是我在基准R中的處理方式。是否有辦法在ggplot2中添加這些顏色標簽?

ggplot2中執行此類操作的自然方式將是在分類變量上創建子圖。 但是,如果要將所有內容都放在同一張圖上,則可以嘗試使用geom_tile()層,如下所示:

df <-data.frame(x = factor(c(4,6,8)), colour = factor(c(1,2,1)))

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
  geom_boxplot()  +
  geom_tile(data=df, aes(x = x, y = 8, fill = colour)) 

在此處輸入圖片說明

或者,如您建議的那樣,您可以在其下方對齊另一個圖。 您可以在ggpubr軟件包中使用ggarrange()

plot1 <- ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
  geom_boxplot()  +
  geom_tile(data=df, aes(x = x, y = 10, fill = colour))
  theme(legend.position = 'none')

plot2 <- ggplot(df, aes(x=x, y=1, fill = colour)) +
  geom_tile() +
  theme_void() +
  scale_fill_manual(values=c('orange', 'green', 'orange')) +
  theme(legend.position = 'none')

library(ggpubr)

ggarrange(plot1, plot2, nrow = 2, heights = c(10, 1), align = 'h')

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM