R語言筆記:用barplot()函數繪製酷炫的柱形圖

2021-12-25 哈佛在等我呢
R語言是一門統計語言。R既可以用來做數據的處理,又可以用來繪製各種各樣簡單的、複雜的可視化圖表。在R中,繪圖的代碼可以說是函數式編程,不像Python一樣,需要寫比較多的邏輯代碼,而是像Excel一樣,通常,我們只需要找到合適的函數,然後往裡面填寫參數即可。本文就以barplot()繪製柱形圖來展開講解。

查看幫助文檔:

文檔內容信息複製粘貼過來,如下:

Argumentsheight  either a vector or matrix of values describing the bars which make up the plot. If height is a vector, the plot consists of a sequence of rectangular bars with heights given by the values in the vector. If height is a matrix and beside is FALSE then each bar of the plot corresponds to a column of height, with the values in the column giving the heights of stacked sub-bars making up the bar. If height is a matrix and beside is TRUE, then the values in each column are juxtaposed rather than stacked.
width optional vector of bar widths. Re-cycled to length the number of bars drawn. Specifying a single value will have no visible effect unless xlim is specified.
space the amount of space (as a fraction of the average bar width) left before each bar. May be given as a single number or one number per bar. If height is a matrix and beside is TRUE, space may be specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups. If not given explicitly, it defaults to c(0,1) if height is a matrix and beside is TRUE, and to 0.2 otherwise.
names.arg a vector of names to be plotted below each bar or group of bars. If this argument is omitted, then the names are taken from the names attribute of height if this is a vector, or the column names if it is a matrix.
legend.text a vector of text used to construct a legend for the plot, or a logical indicating whether a legend should be included. This is only useful when height is a matrix. In that case given legend labels should correspond to the rows of height; if legend.text is true, the row names of height will be used as labels if they are non-null.
beside a logical value. If FALSE, the columns of height are portrayed as stacked bars, and if TRUE the columns are portrayed as juxtaposed bars.
horiz a logical value. If FALSE, the bars are drawn vertically with the first bar to the left. If TRUE, the bars are drawn horizontally with the first at the bottom.
density a vector giving the density of shading lines, in lines per inch, for the bars or bar components. The default value of NULL means that no shading lines are drawn. Non-positive values of density also inhibit the drawing of shading lines.
angle the slope of shading lines, given as an angle in degrees (counter-clockwise), for the bars or bar components.
col a vector of colors for the bars or bar components. By default, grey is used if height is a vector, and a gamma-corrected grey palette if height is a matrix.
border the color to be used for the border of the bars. Use border = NA to omit borders. If there are shading lines, border = TRUE means use the same colour for the border as for the shading lines.
main,sub overall and sub title for the plot.
xlab a label for the x axis.
ylab a label for the y axis.
xlim limits for the x axis.
ylim limits for the y axis.
xpd logical. Should bars be allowed to go outside region?
log string specifying if axis scales should be logarithmic; see plot.default.
axes logical. If TRUE, a vertical (or horizontal, if horiz is true) axis is drawn.
axisnames logical. If TRUE, and if there are names.arg (see above), the other axis is drawn (with lty = 0) and labeled.
cex.axis expansion factor for numeric axis labels.
cex.names expansion factor for axis names (bar labels).
inside logical. If TRUE, the lines which divide adjacent (non-stacked!) bars will be drawn. Only applies when space = 0 (which it partly is when beside = TRUE).
plot logical. If FALSE, nothing is plotted.
axis.lty the graphics parameter lty applied to the axis and tick marks of the categorical (default horizontal) axis. Note that by default the axis is suppressed.
offset a vector indicating how much the bars should be shifted relative to the x axis.
add logical specifying if bars should be added to an already existing plot; defaults to FALSE.
ann logical specifying if the default annotation (main, sub, xlab, ylab) should appear on the plot, see title.
args.legend list of additional arguments to pass to legend(); names of the list are used as argument names. Only used if legend.text is supplied.
formula a formula where the y variables are numeric data to plot against the categorical x variables. The formula can have one of three forms:
y ~ x y ~ x1 + x2 cbind(y1, y2) ~ x, see the examples.
data a data frame (or list) from which the variables in formula should be taken.
subset an optional vector specifying a subset of observations to be used.
na.action a function which indicates what should happen when the data contain NA values. The default is to ignore missing values in the given variables.
... arguments to be passed to/from other methods. For the default method these can include further arguments (such as axes, asp and main) and graphical parameters (see par) which are passed to plot.window(), title() and axis.
ValueA numeric vector (or matrix, when beside = TRUE), say mp, giving the coordinates of all the bar midpoints drawn, useful for adding to the graph.
If beside is true, use colMeans(mp) for the midpoints of each group of bars, see example.
Author(s)R Core, with a contribution by Arni Magnusson.
ReferencesBecker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
Murrell, P. (2005) R Graphics. Chapman & Hall/CRC Press.
See Alsoplot(..., type = "h"), dotchart; hist for bars of a continuous variable. mosaicplot(), more sophisticated to visualize several categorical variables.
Examples# Formula methodbarplot(GNP ~ Year, data = longley)barplot(cbind(Employed, Unemployed) ~ Year, data = longley)
## 3rd form of formula - 2 categories :op <- par(mfrow = 2:1, mgp = c(3,1,0)/2, mar = .1+c(3,3:1))summary(d.Titanic <- as.data.frame(Titanic))barplot(Freq ~ Class + Survived, data = d.Titanic, subset = Age == "Adult" & Sex == "Male", main = "barplot(Freq ~ Class + Survived, *)", ylab = "# {passengers}", legend = TRUE)# Corresponding table :(xt <- xtabs(Freq ~ Survived + Class + Sex, d.Titanic, subset = Age=="Adult"))# Alternatively, a mosaic plot :mosaicplot(xt[,,"Male"], main = "mosaicplot(Freq ~ Class + Survived, *)", color=TRUE)par(op)

# Default methodrequire(grDevices) # for colourstN <- table(Ni <- stats::rpois(100, lambda = 5))r <- barplot(tN, col = rainbow(20))#- type = "h" plotting *is* 'bar'plotlines(r, tN, type = "h", col = "red", lwd = 2)
barplot(tN, space = 1.5, axisnames = FALSE, sub = "barplot(..., space= 1.5, axisnames = FALSE)")
barplot(VADeaths, plot = FALSE)barplot(VADeaths, plot = FALSE, beside = TRUE)
mp <- barplot(VADeaths) # defaulttot <- colMeans(VADeaths)text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")barplot(VADeaths, beside = TRUE, col = c("lightblue", "mistyrose", "lightcyan", "lavender", "cornsilk"), legend = rownames(VADeaths), ylim = c(0, 100))title(main = "Death Rates in Virginia", font.main = 4)
hh <- t(VADeaths)[, 5:1]mybarcol <- "gray20"mp <- barplot(hh, beside = TRUE, col = c("lightblue", "mistyrose", "lightcyan", "lavender"), legend = colnames(VADeaths), ylim = c(0,100), main = "Death Rates in Virginia", font.main = 4, sub = "Faked upper 2*sigma error bars", col.sub = mybarcol, cex.names = 1.5)segments(mp, hh, mp, hh + 2*sqrt(1000*hh/100), col = mybarcol, lwd = 1.5)stopifnot(dim(mp) == dim(hh)) # corresponding matricesmtext(side = 1, at = colMeans(mp), line = -2, text = paste("Mean", formatC(colMeans(hh))), col = "red")
# Bar shading examplebarplot(VADeaths, angle = 15+10*1:5, density = 20, col = "black", legend = rownames(VADeaths))title(main = list("Death Rates in Virginia", font = 4))
# Border colorbarplot(VADeaths, border = "dark blue")

# Log scales (not much sense here)barplot(tN, col = heat.colors(12), log = "y")barplot(tN, col = gray.colors(20), log = "xy")
# Legend locationbarplot(height = cbind(x = c(465, 91) / 465 * 100, y = c(840, 200) / 840 * 100, z = c(37, 17) / 37 * 100), beside = FALSE, width = c(465, 840, 37), col = c(1, 2), legend.text = c("A", "B"), args.legend = list(x = "topleft"))

構造數據:

# 構造數據x <- c(100, 130, 169, 220, 286, 372, 484, 629, 818, 1063, 1382, 1797)y <- c("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月")

01 開始繪製柱形圖


1. barplot() : 繪製一個最簡單的柱形圖:

# 1. barplot() : 繪製一個最簡單的柱形圖barplot(x)

運行結果:

2.  names.arg = "" :給每根柱子添加類別名稱:

# 2. names.arg = "" :給每根柱子添加類別名稱barplot(x,names.arg = y)

運行結果:

3.  col = "" : 把柱形圖統一改成藍色

# 3. col = "" : 把柱形圖統一改成藍色barplot(x,names.arg = y,col = "blue")

運行結果:

4.  col = rainbow(數量) : 把柱形圖改成彩虹色(注意數組下標越界):

# 4. col = rainbow(數量) : 把柱形圖改成彩虹色(注意數組下標越界)barplot(x,names.arg = y,col = rainbow(12))

運行結果:

5.  colors <- c(顏色序列):  自定義每根柱子的顏色:

# 5. colors <- c(顏色序列) : 自定義每根柱子的顏色colors <- c("#4E79A7",  "#A0CBE8",  "#F28E2B",  "#FFBE7D",  "#59A14F",  "#8CD17D",  "#B6992D",  "#F1CE63",  "#499894",  "#86BCB6",  "#E15759",  "#E19D9A")barplot(x,names.arg = y,col = colors)

運行結果:

6.  border = "blue" : 把邊框線顏色調為藍色

# 6. border = "blue" : 把邊框線顏色調為藍色barplot(x,names.arg = y,col = colors,border = "blue")

運行結果:

7.  border = "NA" : 為了顯得更美觀,把柱形圖的邊框線消掉

# 7. border = "NA" : 為了顯得更美觀,把柱形圖的邊框線消掉barplot(x,names.arg = y,col = colors,border = "NA")

運行結果:

8.  main = "主標題名稱" :  添加主標題

# 8.  main = "主標題名稱" : 添加主標題barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)")

運行結果:

9.  sub = "副標題名稱" :  添加副標題

# 9. sub = "副標題名稱" : 添加副標題barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢")

運行結果:

10.  ylab = "Y軸標籤信息" : 給y軸加標籤

# 10. ylab = "Y軸標籤信息" : 給y軸加標籤barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)")

運行結果:

11.  xlab = "X軸標籤" : 給x軸加標籤

# 11. xlab = "X軸標籤" : 給x軸加標籤barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份")

運行結果:


12. horiz = TRUE/FASLE : 調整為水平柱形圖

# 12. horiz = TRUE/FASLE : 調整為水平柱形圖barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE)

運行結果:

13. density = "數量" : 設置底紋的密度

# 13. density 設置底紋的密度barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100)

運行結果:


14. angle = "數字": 設置底紋的斜率

# 14. angle 設置底紋的斜率barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100,angle = 30)

運行結果:

15. las =0/1(縱向/橫向) : 設置坐標軸標籤的方向

# 15. las =0/1(縱向/橫向) : 設置坐標軸標籤的方向barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100,angle = 30,las = 1)

運行結果:


16. space ="數字(值越大,間隔越大)" : 各個條形間的寬度(間隔)

# 16. space ="數字(值越大,間隔越大)" : 各個條形間的寬度(間隔)barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100,angle = 30,las = 1,space = 0.6)

運行結果:

17.  axisnames = FALSE/TRUE : 是否顯示條形標籤

# 17. axisnames = FALSE/TRUE : 是否顯示條形標籤barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100,angle = 30,las = 1,space = 0.6,axisnames = FALSE)

運行結果:

18. legend.text  = "傳參" : 添加圖例文本

# 18. legend.text  添加圖例文本barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份", horiz = TRUE,density = 100,angle = 30,las = 1,space = 0.6,axisnames = FALSE,legend.text = x)

運行結果:

19. cex.names = "數字(數值越大,字體越大)" : 控制類別名稱字體的大小

# 19. cex.names = "數字(數值越大,字體越大)" : 控制類別名稱字體的大小barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份",cex.names = 1.5)

運行結果:

20. cex.axis  = "數字(數值越大,字體越大)" : 控制Y軸比例尺數值的大小

# 20. cex.axis  = "數字(數值越大,字體越大)" : 控制Y軸比例尺數值的大小barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份",cex.names = 1.5,cex.axis = 0.8)

運行結果:

20. axisnames = FALSE :不顯示X軸類別名稱

# 21. axisnames = FALSE :不顯示X軸類別名稱barplot(x,names.arg = y,col = colors,border = "NA",main = "2020年各個月份的銷售額(萬元)",sub = "哈佛在等我呢",ylab = "銷量(萬元)",xlab = "月份",cex.names = 1.5,cex.axis = 0.8,axisnames = FALSE)

運行結果:

若感興趣,大家可複製、粘貼以上代碼,自行學習。代碼皆源自本人去年所學,並於最近花了兩三天的時間調試、編寫出來。可見,有時候寫代碼並非都代表效率高!如本文中的操作,還不如直接使用Excel,反而更快捷,美觀度也不輸用代碼繪製。具體操作如下圖視頻及連結所示,皆由本人憑基礎親自製作,分享給大家:

學習連結:

https://www.bilibili.com/video/BV11Q4y1f7VH?spm_id_from=333.999.0.0

溫馨提示:連結視頻下方評論區有模板獲取地址

溫馨提示:

視頻中Excel可視化模板的獲取連結請詳見以下連結的評論區:

https://www.bilibili.com/video/BV11Q4y1f7VH?spm_id_from=333.999.0.0

註:本文源於我平時所學,於這兩天整理、歸納、總結出來的學習筆記。因在在多數企業中,工作一般不使用R語言繪圖(Excel, Tableau, BI, 以及其它工具用得比較多。大家可自行挑選一兩款用得比較順手的工具來上手即可。在這裡,我首推Excel。一來,在各行各業的辦公崗位中,Excel的使用頻率特別高,二來,用Excel也可以製作出好看的基礎可視化圖表),所以尚有諸多參數未能一一列舉出來。另外本人所學有限,本文只是拋磚引玉,大家如對R語言可視化感興趣,可自行參照幫助文檔進行更加全面的學習。

感謝閱讀!

相關焦點

  • R語言中繪製條形圖的函數:barplot
    條形圖(bar chart)是用寬度相同的條形的高度或長短來表示數據多少的圖形。它主要用來展示不同分類(橫軸)下某個數值型變量(縱軸)的取值。在實際中,條形圖主要有簡單條形圖,組合條形圖和堆疊條形圖。在R語言的基礎包中可以使用barplot()函數來繪製條形圖。
  • 【R語言】--- graphics包的barplot()函數繪製柱狀圖
    柱狀圖又叫條形圖,是數據展示最重要的一類統計圖,數據分析結果展示中使用頻率非常高,各類統計軟體均能繪製。在R語言中,有很多包可繪製柱狀圖,比如graphics包barplot()函數和ggplot2包geom_bar()函數。 本文介紹graphics包的barplot()函數繪製柱狀圖。
  • 用R語言繪製條形圖
    雖然我本人會用Python的matplotlib和pyecharts,百度的Echarts,微軟的Excel作可視化圖形,但因為自身也是學統計學專業的,如果不會用R語言。心裡多少都會感到有一點遺憾。        經過我這兩天的,摸索,其實發現「可視化之神」也不難上手,只要多「百度經驗」和「CSDN」一下就可以了。閒話少說,來點乾貨先。
  • R語言繪圖(一):barplot()繪製條形圖
    條形圖:表示矩形條中的數據,條的長度與變量的值成比例。R語言中bartplot()函數可用於創建條形圖。
  • 【R語言】--- ggplot2包的geom_bar()函數繪製柱狀圖
    柱狀圖又叫條形圖,是數據展示最重要的一類統計圖,數據分析結果展示中使用頻率非常高,各類統計軟體均能繪製。在R語言中,有很多包可繪製柱狀圖,比如graphics包barplot()函數和ggplot2包geom_bar()函數。本文介紹ggplot2包的geom_bar()函數繪製柱狀圖。
  • R語言學習第4天--barplot()繪製堆砌條形圖
    想了解barplot()函數的用法,1、可以在命令行輸入「?barplot「,點擊「Enter」鍵即可查看說明文檔。2、在命令行輸入「example(barplot)」,之後多次點擊「Enter」即可查看多個例圖及對應的腳本。
  • R語言繪製條形圖
    作者:吳健 中國科學院大學 R語言、統計學愛好者,尤其擅長R語言和Arcgis在生態領域的應用分享個人公眾號:統計與程式語言
  • R語言基礎繪圖barplot與各種條形圖(1)
    此篇主要介紹一下R語言繪製各式的條形圖;需要對R語言有一定的了解,只要有興趣,學習很簡單。
  • R語言基礎繪圖函數繪製帕類託圖(Pareto chart)
    有時候我們會用帕累託圖(Pareto chart)來展現數據的兩個指標(一個頻數,一個率),這種情況就需要用雙坐標來展示。ggplot2的作者Hardley似乎也不太認同雙坐標的存在。那麼,有時候回歸基礎包,也是另一種嘗試。花了點時間用基礎包畫了下面這張帕類託圖,左側縱坐標代表病人例數,右側表示死亡率,橫坐標是一種疾病嚴重程度評分。那麼我們來看一下這麼一張圖是怎麼一步步畫出來的吧。
  • R語言 | R語言繪製抖動散點圖和蜂群圖
    語言自帶的一個小數據集,展示使用ggplot2包繪製兩種特殊的散點統計圖,抖動散點圖(jitter plot)和蜂群圖((beeswarm plot)。 接下來,繪製簡單的統計圖對該數據集進行可視化,以初步查看哪種藥物治療方案更為有效。通常,我們會首選繪製箱線圖、提琴圖或者柱形圖等來展示整體概況,它們包含分位數或者均值等信息,以便初步觀察和比較各藥物治療組的療效的差異。但如果也想將每個個體的響應狀態呈現出來,就需要在圖中添加散點表示每個患者個體,參考以下示例。
  • python數據可視化--matplotlib繪製柱形圖
    柱形圖一般用於類別比較,用柱子的高低來表示數據的大小,在matplotlib中使用plt.bar()函數繪製柱形圖,先看一段代碼:import matplotlib.pyplot as plt plt.rcParams['font.family']='SimHei'label=['語文','數學','英語','歷史']score
  • R語言之plot繪圖函數的使用
    R有強大的繪圖功能,plot()函數是一種常用的繪圖函數,用其可以繪製散點圖、曲線圖等。plot函數的語法格式R語言中plot()函數的基本格式如下:plot(x,y,...)plot函數中,x和y分別表示所繪圖形的橫坐標和縱坐標;函數中的...為附加的參數。
  • 【MATLAB圖像】— 繪製plot與其它二維圖形
    1、最基本的plot函數        格式為:plot(y),plot(x,y),plot(x,y,s),s
  • R語言50繪圖|第一期barplot()條形圖
    接下來幾天帶來《R語言50繪圖》系列~很多小夥伴也都是和我一樣的入門級,有的希望出一些簡單繪圖的教程!那今天就和大家分享一下:barplot()條形圖barplot(height, width = 1, space = NULL, names.arg = NULL, legend.text = NULL,beside = FALSE, horiz = FALSE, density
  • Python-seaborn 基礎圖表繪製-柱形圖(數據分享)
    上期介紹了使用R-ggplot繪製基礎柱形圖的繪製推文,本期按照慣例,我們繼續推出Python 版本的繪製方法,當然我們也是經過美化修飾的結果,畢竟要自己看的過去才行。本期推文主要涉及的知識點如下:Matplotlib inset_locator.inset_axes()自由添加圖片元素Python-seaborn繪製統計直方圖在使用基礎的matplotlib雖然也能繪製出直方統計圖,但面對多類別數據則顯得較為蠻煩,基本系列課程的目的是為了大家系統掌握各種圖表的繪製方法
  • R語言繪製抖動散點圖和蜂群圖
    本篇通過R語言自帶的一個小數據集,展示使用ggplot2包繪製兩種特殊的散點統計圖,抖動散點圖(jitter plot)和蜂群圖((beeswarm
  • 練習R:interaction.plot()函數繪製交互作用圖
    所以我需要針對方差分析交互作用顯著後,直接繪製出有交互作用的兩因素交互圖。
  • Python/R: 森林圖(Forest Plot)的繪製
    今天這篇推文,小編就帶大家了解一下森林圖(Forest Plot) 的繪製方法,主要內容如下:Python-森林圖(Forest Plot)繪製方法森林圖(Forest Plot)的簡單介紹森林圖(Forest Plot) 常用於Meta分析結果展示使用
  • 使用R繪製幾種常用的雙坐標軸圖形
    難道R語言就無法繪製雙軸圖形了嗎?非也,R不僅是統計學家的標準工具,也是一款繪製圖形的理想工具。下面就跟大家介紹plotrix包中的twoord.plot()函數和twoord.stackplot()函數,它們可以實現雙坐標軸圖形的繪製。
  • 每天學習一點R:16.barplot條形圖之整合點線圖
    args.mges.number <- read.table("ARGs.MGEs.abundance.txt",header = TRUE,sep = "\t",row.names = 1)args.16s.abundance <- read.table("ARGs.16S.abundance.txt",header = TRUE