【问题标题】:Inserting a tick mark, as well as xlab in a barplot panel in r在 r 的条形图面板中插入刻度线以及 xlab
【发布时间】:2015-12-10 16:55:26
【问题描述】:

除了xlab 之外,我还想在 3 x 3 条形图面板中包含刻度线。我为单个图尝试了this 解决方案,但不知何故我在复制它时遇到了麻烦。这个想法是用从-3到+3的d标记每个条,增加一个单位。每个图中的第一个条形代表 -3 的值。我试图用下面的模拟数据来证明我的问题。有任何想法吗?

# Data generation

# Populating a matrix
matrix(rnorm(63, 1:9), nrow=7, byrow=TRUE)

# Labelling the matrix
colnames(mat.s) <- c("Hs", "Sex", "Es", "Bo", "R", "W", "S", "Pri", "Abo")

# Tick mark indicator
d <- seq(-3,3,1)

# Plotting estimates
par(mfrow=c(3,3), mar = c(4,3,3,1))

for(i in 1:9) {

# Bar plot
barplot(mat.s[,i],

# X-label
xlab = colnames(mat.s)[i])

}

【问题讨论】:

  • 它必须以 R 为基础吗?你能证明你实施了解决方案吗?
  • 要创建矩阵,可以matrix(rnorm(63, 1:9), nrow=7, byrow=TRUE)

标签: r graph


【解决方案1】:

在循环中的barplot 函数内指定axis.ltynames.argmgp,你会没事的:

#I haven't changed anything else before the for-loop
#only changes have taken place inside the barplot function below
for(i in 1:9) {
  # Bar plot
  barplot(mat.s[,i], xlab = colnames(mat.s)[i], 
          names.arg= as.character(-3:3), axis.lty=1, mgp=c(3,1,0.2))
}

输出:

再详细一点:

  • names.arg 将添加标签
  • axis.lty=1 将添加一个 x 轴
  • mgp 是一个长度为 3 的向量,依次控制标题、标签和轴线的边距。我只需要将其中的第三个元素更改为 0.2,以便轴看起来不错(检查 ?par)。

【讨论】:

  • 非常欢迎您@AlexRead :)。很高兴我能帮上忙!
【解决方案2】:

LyzanderR 的出色答案的替代方法是在将 barplot() 调用分配给对象后添加 axis()

for(i in 1:9) {

  # Bar plot
  temp <- barplot(mat.s[,i],

  # X-label
  xlab = colnames(mat.s)[i])
  axis(1,at=temp,labels=-3:3)
}

【讨论】:

    【解决方案3】:

    这是ggplot 版本:

    library(dplyr)
    library(reshape2)
    library(ggplot2)
    
    # Add x-labels and reshape to long format then plot
    ggplot(mat.s %>% mutate(x=-3:3) %>% melt(id.var="x"), 
           aes(x=x, y=value)) +
      geom_bar(stat="identity", fill=hcl(195,100,65)) +
      facet_wrap(~variable) +
      labs(x="", y="") +
      scale_x_continuous(breaks=-3:3)  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多