• TNT 擂台赛
  • 序言
  • 1 曲线簇
  • 2 直方图的对数坐标
  • 3 绘制地图
  • 4 柱状图的边框
  • 5 从字符串里提取年和月
  • 6 将持续天数转换成每天出现频次
  • 7 从字符串里提取数字并做后续运算
  • 8 数据框筛选重写
  • 9 将数据框分组提取某列最大值并做后续操作
  • 后记
  • Published with bookdown

TNT 擂台赛

4 柱状图的边框

题目4: 下图来自Economisit:

请问,如何在柱状图里指定的某些柱子上显示边框?

# 准备数据
df = mtcars
df$car = rownames(mtcars)
cl_red <- c(2, 4, 6)

N 版

df.o <- df[order(df[,1]), ]
df.o$bd <- "NA"
df.o$bd[cl_red] <- "red"
par(mar = c(12, 4, 1, 1), las = 1)
barplot_car <- 
  barplot(df.o$mpg, border = df.o$bd, 
          col = df.o$cyl, ylab = 'mpg', 
          main = 'Miles per gallon')
legend('topleft', legend = unique(df.o$cyl), 
       fill = unique(df.o$cyl), title = 'cyl', 
       border = NA, bty = 'n')
text(x = barplot_car[cl_red], 
     y = df.o$mpg[cl_red], 
     labels = df.o$hp[cl_red])
mtext('car', 1, 8)
axis(1, at = barplot_car, labels = df.o$car, 
     las = 2)

T 版

require(ggplot2)
require(dplyr)
df.sort = df %>% 
  arrange(mpg)
df.sort %>% 
  ggplot(aes(x=car,y=mpg,fill=cyl))+
  geom_col()+
  geom_col(data= df.sort[cl_red,], 
           color="red", size=1)+
  geom_text(data= df.sort[cl_red,], 
            aes(label=hp))+
  scale_x_discrete(limits= df.sort$car) +
  theme_classic()+
  theme(axis.text.x = 
          element_text(angle = 90, hjust = 1))+
  ggtitle("Miles per gallon")


  1. 贡献者为 @seeyou14 @tctcab @Liechi 等,来自 https://d.cosx.org/d/421117。↩