r中的barplot标签:使用text()显示旋转标签的问题

时间:2014-12-18 16:35:32

标签: r text label bar-chart labels

我想在条形图的列中添加标签。由于有两组,每对列将共享相同的标签,即7个标签从“非常不喜欢”到“非常好”。

由于标签标题很长,我打算使用text()函数旋转它们,但我无法正确显示它。这是代码:

A <- c(0, 1, 0, 1, 14, 44, 42)
B <- c(0, 0, 0, 2, 14, 41, 45)

x <- rbind(A, B)

dd.names <- c("Dislike very much", "Strongly dislike", "Dislike", "Neither like nor dislike", "Like", "Like well", "Like very well")

bp <- barplot(x,
              beside = TRUE, # Plot the bars beside one another; default is to plot stacked bars 
              space=c(0.2,0.8), # Amount of space between i) bars within a group, ii) bars between groups
              legend = c("Fish cake containing sugar kelp", "Control fish cake"),
              args.legend = list(x = "topleft", bty = "n", inset=c(0.1, 0.1)), # bty removes the frame from the legend
              xlab = "",
              ylab = "Number of scores",
              ylim = range(0:50), # Expand the y axis to the value 50
              main = "Score results from taste experiments of fish cakes")

text(bp, par("usr")[1], pos = 1, offset = 2, labels = dd.names, adj = 0.5, srt = 25, cex = 0.8, xpd = TRUE)

1 个答案:

答案 0 :(得分:1)

IMO你最好旋转图表。

par(mar=c(3,8,1,1),mgp=c(1.5,.5,0))
bp <- barplot(x,
              beside = TRUE,
              space=c(0.2,0.8), 
              legend = c("Fish cake containing sugar kelp", "Control fish cake"),
              args.legend = list(x = "bottom", bty = "n", inset=c(0.1, 0.1)),
              ylab = "",
              xlab = "Number of scores",
              xlim = range(0:50), # Expand the y axis to the value 50
              main = "Score results from taste experiments of fish cakes",
              horiz = TRUE)
text(rep(0,length(dd.names)),bp[1,], par("usr")[3], pos = 2, 
     labels = dd.names, cex = 0.8, xpd = TRUE)

在未经请求的传福音行为中,这是一个ggplot解决方案。

library(ggplot2)
library(reshape2)   # for melt(...)
library(grid)       # for unit(...)
gg <- melt(data.frame(dd.names,t(x)),id="dd.names")
gg$dd.names <- with(gg,factor(dd.names,levels=unique(dd.names)))

ggplot(gg,aes(x=dd.names,y=value))+
  geom_bar(aes(fill=variable),stat="identity",position="dodge")+
  coord_flip()+
  scale_fill_manual(name="",values=c("grey30","grey70"),
                    labels=c("Fish cake containing sugar kelp", "Control fish cake"))+
  labs(title="Score results from taste experiments of fish cakes",
       x="",y="Number of scores")+
  theme_bw()+theme(legend.position = c(1,0),legend.justification = c(1,0),
                   legend.key.height=unit(0.8,"lines"))