要点
- 根据具体情况调整长宽比
- 最好柱子高度按照降序排列
- 所有柱子应该是同一种颜色(可以特殊颜色标记某几个焦点柱子)
- 如果柱子是左对齐的(横柱子)则其轴标签需要右对齐,以减少视觉空白区域
- 轴标签字体大小与柱子的宽度对应
- 需要标注特殊柱子时,可以使用不同颜色区分,也可以同时对其轴标签使用加粗字体(使用的字体多于两种cut,不仅仅只有regular和bold,如Lato字体有light、black等5个不同粗细的选择)
- 添加一条参考线(如平均值等)
- 背景分块可以快速定位柱子高度(也可以添加网格线)
- 如果数据是百分数,则不必每个数值后面都加上百分号,只需在某个合适位置备注一下“all values in percent”即可
实例1
效果图:
在网站http://www.latofonts.com/上下载Lato字体并安装(复制到C:\Windows\Fonts\目录下即可)
绘图代码:
pdf_file <- "barcharts_simple.pdf"
cairo_pdf(bg = "grey98", pdf_file, width = 9, height = 6.5)
par(omi = c(0.65, 0.25, 0.75, 0.75), mai = c(0.3, 2, 0.35, 0),
mgp = c(3, 3, 0), family = "Lato Light", las = 1)
# 导入数据
# library(gdata)
# ipsos <- read.xls("myData/ipsos.xlsx", encoding = "latin1")
load(url("https://github.com/x2yline/Rdata/raw/master/data%20visualization%20R/6_1_ipsos.RDATA"))
sort.ipsos <- ipsos[order(ipsos$Percent), ]
attach(sort.ipsos)
# Create chart
x <- barplot(Percent, names.arg = F, horiz = T, border = NA,
xlim = c(0, 100), col = "grey", cex.names = 0.85, axes = F)
# Label chart
for (i in 1:length(Country)) {
if (Country[i] %in% c("Germany", "Brazil")) {
myFont <- "Lato Black"
} else {
myFont <- "Lato Light"
}
text(-8, x[i], Country[i], xpd = T, adj = 1, cex = 0.85,
family = myFont)
text(-3.5, x[i], Percent[i], xpd = T, adj = 1, cex = 0.85,
family = myFont)
}
# Other elements
rect(0, -0.5, 20, 28, col = rgb(191, 239, 255, 80, maxColorValue = 255),
border = NA)
rect(20, -0.5, 40, 28, col = rgb(191, 239, 255, 120, maxColorValue = 255),
border = NA)
rect(40, -0.5, 60, 28, col = rgb(191, 239, 255, 80, maxColorValue = 255),
border = NA)
rect(60, -0.5, 80, 28, col = rgb(191, 239, 255, 120, maxColorValue = 255),
border = NA)
rect(80, -0.5, 100, 28, col = rgb(191, 239, 255, 80, maxColorValue = 255),
border = NA)
myValue2 <- c(0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0,
0)
myColour2 <- rgb(255, 0, 210, maxColorValue = 255)
x2 <- barplot(myValue2, names.arg = F, horiz = T, border = NA,
xlim = c(0, 100), col = myColour2, cex.names = 0.85, axes = F,
add = T)
arrows(45, -0.5, 45, 20.5, lwd = 1.5, length = 0, xpd = T, col = "skyblue3")
arrows(45, -0.5, 45, -0.75, lwd = 3, length = 0, xpd = T)
arrows(45, 20.5, 45, 20.75, lwd = 3, length = 0, xpd = T)
text(41, 20.5, "Average", adj = 1, xpd = T, cex = 0.65, font = 3)
text(44, 20.5, "45", adj = 1, xpd = T, cex = 0.65, family = "Lato",
font = 4)
text(100, 20.5, "All values in percent", adj = 1, xpd = T, cex = 0.65,
font = 3)
mtext(c(0, 20, 40, 60, 80, 100), at = c(0, 20, 40, 60, 80, 100),
1, line = 0, cex = 0.8)
# Titling
mtext("'I Definitely Believe in God or a Supreme Being'", 3,
line = 1.3, adj = 0, cex = 1.2, family = "Lato Black", outer = T)
mtext("was said in 2010 in:", 3, line = -0.4, adj = 0, cex = 0.9,
outer = T)
mtext("Source: www.ipsos-na.com, Design: Stefan Fichtel, ixtract",
1, line = 1, adj = 1, cex = 0.65, outer = T, font = 3)
dev.off()
注:
如果不使用cairo_pdf输出图形而使用默认窗口则会有字体报错(因为windows默认窗口不支持字体嵌入)
不使用一次性上色方案是为了避免背景色把需要特殊标记的柱子挡住(有绘制的先后问题)