• R语言
  • 【已解决】barplot绘图:如何调整y轴类别标签的距离

Maple
回避这个问题的方案

data(NCI60,package ="ISLR") # 加载数据
dat <- as.data.frame(table(NCI60$labs))
order_dat <- dat[order(dat$Freq,decreasing = TRUE),]
num <- order_dat[,2]
names(num) <- order_dat[,1]
op <- par(mar=c(2,1,1,1))
plot(c(0,10),c(0,17),type="n",axes = FALSE,ann=FALSE)
xlabs <- seq(0,10,by=1)
axis(1, labels = xlabs, at = xlabs, las = 1) # x-axis
mycolors <- yarrr::piratepal(palette = "info2") 
barplot(num,add=TRUE,col=mycolors,axes = FALSE,
axisnames=FALSE,border ="white",
args.legend=list(border = "white",box.col="white"),
horiz=TRUE,xlab="numbers",ylab="",legend.text = TRUE)
box(col = "gray")
par(op)

barplot2

Maple

想了想,这图有搞得人眼花缭乱之嫌,
曾几何时我也不是ggplot2党,还有一点强迫症,这下满意了

data(NCI60,package ="ISLR") # 加载数据
dat <- as.data.frame(table(NCI60$labs))
order_dat <- dat[order(dat$Freq,decreasing = TRUE),]
num <- order_dat[,2]
names(num) <- order_dat[,1]
op <- par(mar=c(2,7,1,1))
plot(c(0,10),c(0,17),type="n",axes = FALSE,ann=FALSE)
xlabs <- seq(0,10,by=1) # 下面一行是关键
ylabs <- seq(0.7,length(num)+2.3,length.out=length(num))
ylabs_names <- names(num)
axis(1, labels = xlabs, at = xlabs, las = 1,col = "gray") # xaxis
axis(2, labels = ylabs_names, at = ylabs, las = 1,col="white")
barplot(num,add=TRUE,col="lightblue",axes = FALSE,
		axisnames=FALSE,border ="white",
		horiz=TRUE,xlab="numbers",ylab="")

barplot3

    Cloud2016 这才是正确的作图方式。那个用颜色图例的方式简直太反人类……

      yihui 的赞,让我觉得代码中0.7和2.3等试出来(瞎蒙的)的数字,情何以堪。遂决定把这个问题磕到底,代码也清净了

      data(NCI60,package ="ISLR") # 加载数据		
      myData <- sort(table(NCI60$labs))		
      par(mar=c(5,2.5,1,1))	
      barCenters <- barplot(myData,col = "lightblue",axes = FALSE,
      			axisnames=FALSE,border ="white")				
      text(x = barCenters, y = par("usr")[3]-.2, srt = 45,
           adj = 1, labels = names(myData), xpd = TRUE)
      axis(2, labels = seq(0,9,by=1), at = seq(0,9,by=1),  las = 1 , col = "gray") 

      请看正图
      barplot4

      再横着来

      data(NCI60,package ="ISLR") # 加载数据		
      myData <- sort(table(NCI60$labs), decreasing = TRUE)		
      par(mar=c(2,7,1,1))	
      barCenters <- barplot(myData,col = "lightblue",axes = FALSE,
      			axisnames=FALSE,horiz=TRUE,border ="white")				
      text(y = barCenters, x = par("usr")[3],
           adj = 1, labels = names(myData), xpd = TRUE)
      axis(1, labels = seq(0,9,by=1), at = seq(0,9,by=1),  las = 1 , col = "gray") 

      看图
      barplot5

        Cloud2016 我觉得凡是需要把坐标轴上的文本标签倾斜甚至是竖过来的情况下,条形图都应该换成躺着放。没有人愿意歪着脑袋看文本标签。

          yihui 我觉得说不定老外习惯了阅读躺着的字母,就像古人和港台习惯竖着读书一样,要不没法理解书店或图书馆外文书书脊上的字。

          yihui 数字像日期,我觉得没事,文本可能不合适躺着。
          img

          Cloud2016 更改标题为「【已解决】barplot绘图:如何调整y轴类别标签的距离