簡體   English   中英

ggplot2:防止geom_bar按字母順序排列,並且y比例不顯示中斷

[英]ggplot2: Prevent geom_bar from being alphabetical, and y scale not showing breaks

我的ggplot有兩個問題。

數據:

> dput(cts2)
structure(list(country_name = c("United States", "Canada", "India", 
"Bots", "Estonia", "Mexico", "Portugal", "Finland", "United Kingdom", 
"New Zealand", "Australia", "Russia", "Denmark", "Sweden", "Poland", 
"Ireland", "Ghana", "Netherlands", "Chile", "Other"), freq = c(716288L, 
77290L, 14925L, 12393L, 9526L, 9307L, 9003L, 6733L, 6174L, 3860L, 
3706L, 3553L, 3444L, 2371L, 1768L, 1532L, 523L, 286L, 234L, 909L
)), row.names = c(54L, 9L, 24L, 55L, 14L, 32L, 39L, 15L, 53L, 
34L, 3L, 44L, 13L, 49L, 38L, 25L, 19L, 33L, 10L, 27L), class = "data.frame")

如您所見,數據已經按照我想要的順序排列了。 最高到最低,但應在末尾的“其他”除外。 現在,當我使用geom_bar嘗試一個簡單的ggplot時:

ggplot(cts2, aes(x=factor(country_name), y=freq)) +
  geom_bar(stat="identity")+ 
  scale_y_continuous(trans='sqrt', labels = scales::comma, breaks = c(400, 10000, 100000, 700000))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

在此處輸入圖片說明

結果有兩個主要問題。

  1. 條形按字母順序排列。 在查看有關此問題的其他問題時,答案始終是“ use stat="identity" '或“ use a factor”。 好了,正如您所看到的,我兩者都沒有效果。
  2. Y比例尺不顯示400的水平。400本身是任意的,因為我想添加很多休息時間。 最終的條形圖將是一個大圖像,因此有空間可以顯示更多細節。

關於Y刻度,即使使用trans='sqrt' ,美國數據點的確很難看到其余數據項之間的差異。 有沒有更好的可視化方法? Log2和Log10看起來都更糟。

您需要設置因子levels 我的猜測是,設置400個標簽不會留出足夠的空間來打印標簽而不會變成負片。 在sqrt變換下不能存在負數。

ggplot(data = cts2, aes(x=factor(country_name, levels = c(unique(cts2$country_name))), y=freq)) +
  geom_bar(stat="identity")+ 
  scale_y_continuous(trans='sqrt', labels = scales::comma, breaks = c(100, 10000, 100000, 700000))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

請參閱: 使用ggplot2,我可以在軸上插入一個中斷嗎? 有關如何處理如此巨大差距的一些想法。 特別是, gap.barplot從庫plotrix將允許你把你的條形圖中的空白。

建議的另一種方法是有一個簡單的表。 您可以在庫gridExtra使用grid.table從數據gridExtra創建一個漂亮的表。

暫無
暫無

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

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