ggplot2——柱狀圖__R

來源:互聯網
上載者:User
目錄: 初始圖樣 如何修改柱條的寬度 如何修改柱條的順序 如何在柱條上添加文字

(更多關於圖例、座標系等內容請見:R、ggplot2、shiny 匯總)


初始圖樣:

library(ggplot2)library(ggthemes)dt = data.frame(obj = c('A','D','B','E','C'), val = c(2,15,6,9,7))p = ggplot(dt, aes(x = obj, y = val, fill = obj, group = factor(1))) +     geom_bar(stat = "identity") +    theme_economist()p


如何修改柱條的寬度:

library(ggplot2)library(ggthemes)dt = data.frame(obj = c('A','D','B','E','C'), val = c(2,15,6,9,7))p = ggplot(dt, aes(x = obj, y = val, fill = obj, group = factor(1))) +     geom_bar(stat = "identity", width = 0.5) +   ## 修改柱條的寬度    theme_economist()p


如何修改柱條的順序:

library(ggplot2)library(ggthemes)dt = data.frame(obj = c('A','D','B','E','C'), val = c(2,15,6,9,7))dt$obj = factor(dt$obj, levels=c('D','B','C','A','E'))   ## 設定柱條的順序p = ggplot(dt, aes(x = obj, y = val, fill = obj, group = factor(1))) +     geom_bar(stat = "identity", width = 0.5) +   ## 修改柱條的寬度    theme_economist()p## 特註:dt$obj 是因子類型,ggplot2作圖的順序就是按照這個因子水平的順序來的,## 所以我們修改因子水平的順序即可修改作圖的順序,具體情況可以輸出一下 dt$obj 。


如何在柱條上添加文字:

library(ggplot2)library(ggthemes)dt = data.frame(obj = c('A','D','B','E','C'), val = c(2,15,6,9,7))dt$obj = factor(dt$obj, levels=c('D','B','C','A','E'))   ## 設定柱條的順序p = ggplot(dt, aes(x = obj, y = val, fill = obj, group = factor(1))) +     geom_bar(stat = "identity", width = 0.5) +   ## 修改柱條的寬度    theme_economist() +     geom_text(aes(label = val, vjust = -0.8, hjust = 0.5, color = obj), show_guide = FALSE) +   ## 顯示柱條上的數字    ylim(min(dt$val, 0)*1.1, max(dt$val)*1.1)   ## 加大 Y 軸的範圍,防止數字顯示不齊全p



轉載請註明出處,謝謝。(原文連結:http://blog.csdn.net/bone_ace/article/details/47267981)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.