sec_axis ggplo2 繪制分面雙坐標(biāo)圖

數(shù)據(jù)構(gòu)建來源:

https://stackoverflow.com/questions/26917689/how-to-use-facets-with-a-dual-y-axis-ggplot

library(ggplot2)


dt.diamonds <- data.table::as.data.table(diamonds)

d1 <- dt.diamonds[,list(revenue = sum(price),
                        stones = length(price)),
                  by = c("clarity","cut")]


max_stones <- max(d1$stones)
max_revenue <- max(d1$revenue)


d2 <- gather(d1, 'var', 'val', stones:revenue) %>% 
  mutate(val = if_else(var == 'revenue', as.double(val), val / (max_stones / max_revenue)))

ggplot() +
  # 柱狀圖數(shù)據(jù)
  geom_bar(data = filter(d2, var == 'revenue'), 
           aes(clarity, val, fill = cut),
           col = "black",
           stat = "identity") +
  # 折線圖數(shù)據(jù)
  geom_line(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
            col = "red", size = 1) +
  geom_point(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
            col = "blue", size = 2) +
  facet_grid(cut~.) +
  # 對調(diào) xy 軸
  coord_flip() +
  # 繪制第二個 x 軸,且原本的 x 軸放置于最上面
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max_stones / max_revenue),
                                         name = 'number of stones'),
                     labels = scales::dollar,
                     position = "right",
                     expand = c(0, 0)) +
  # 原本的 y 軸放置到最左邊
  scale_x_discrete(position = "bottom") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "#F3F2EE", colour = "#F3F2EE"),
        panel.grid.major = element_line(size = 1, linetype = 'solid',
                                        colour = "white"), 
        panel.grid.minor = element_line(size = 1, linetype = 'solid',
                                        colour = "white"),
        axis.text.x = element_text(angle = 0, hjust = 0.5),
        axis.text.y = element_text(color = "blue"),
        # axis.text.y.right = element_text(color = "red"),
        legend.position = "bottom",
        strip.text.y = element_text(angle = 0, color = "black",
                                    face = "bold", size = 12)) +
  labs(x = "")

strip.text.y 用來控制分面后標(biāo)簽文本的具體信息:
比如上面 strip.text.y 換成

strip.text.y = element_text(angle = -90, color = "black",
                                    face = "bold", size = 12))

如果我想將標(biāo)簽放在左邊,且水平放置呢?

strip.text.y.left 和 strip.placement 至關(guān)重要的參數(shù)

ggplot() +
  # 柱狀圖數(shù)據(jù)
  geom_bar(data = filter(d2, var == 'revenue'), 
           aes(clarity, val, fill = cut),
           col = "black",
           stat = "identity") +
  # 折線圖數(shù)據(jù)
  geom_line(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
            col = "red", size = 1) +
  geom_point(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
             col = "blue", size = 2) +
  facet_grid(cut~.,
             switch = "y") +
  # 對調(diào) xy 軸
  coord_flip() +
  # 繪制第二個 x 軸,且原本的 x 軸放置于最上面
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max_stones / max_revenue),
                                         name = 'number of stones'),
                     labels = scales::dollar,
                     position = "right",
                     expand = c(0, 0)) +
  # 原本的 y 軸放置到最左邊
  scale_x_discrete(position = "bottom") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "#F3F2EE", colour = "#F3F2EE"),
        panel.grid.major = element_line(size = 1, linetype = 'solid',
                                        colour = "white"), 
        panel.grid.minor = element_line(size = 1, linetype = 'solid',
                                        colour = "white"),
        axis.text.x = element_text(angle = 0, hjust = 0.5),
        axis.text.y = element_text(color = "blue"),
        # axis.text.y.right = element_text(color = "red"),
        legend.position = "bottom",
        strip.background = element_blank(),
        strip.placement  = "outside",
        strip.text.y.left = element_text(angle = 0, color = "black",
                                    face = "bold", size = 12)) +
  labs(x = "")

如果標(biāo)簽文本過才需要換行呢?

這里給了一個答案:

How to Fit Long Text into Ggplot2 facet Titles

解決方案,就在將分面的文本預(yù)先用 str_wrap() 函數(shù)進(jìn)行分行處理

library(reshape2)
library(ggplot2)

Example<-data.frame(Year,Q1,Q2, stringsAsFactors=FALSE)

ExampleM<-melt(Example,id.vars=c("Year"))

# Helper function for string wrapping. 
# Default 20 character target width.
swr = function(string, nwrap=20) {
  paste(strwrap(string, width=nwrap), collapse="\n")
}
swr = Vectorize(swr)

# Create line breaks in Year
ExampleM$Year = swr(ExampleM$Year)

ggplot(ExampleM, aes(x=variable, fill=value)) + 
  geom_bar(position="dodge") + 
  facet_grid(~Year)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容