【问题标题】:Plot bars starting from x axis not equal to 0 and extend to both sides从不等于 0 的 x 轴开始绘制条并延伸到两侧
【发布时间】:2015-05-23 15:23:46
【问题描述】:

假设我的数据值是

  x <- c(30,50,70,120,150)

我希望它们采用水平格式 (horiz=T)​​。 现在我的 y 轴位置在 x=100,我希望条形图从 x=100 开始,而不是从 0 开始,它应该延伸到左侧和右侧 怎么办?

x=c(30,50,70,120,150)
barplot(x,horiz=T)
axis(2,pos=100)

但这从零开始并扩展到 30、50、70、120 等。我想要的是条形应该从 x=100 开始,左侧延伸 30,50,70,右侧延伸 100+ 值

【问题讨论】:

  • x=c(30,50,70,120,150) barplot(x,horiz=T)​​ axis(2,pos=100) 但这从零开始延伸到 30, 50,70,120 等。我想要的是条形应该从 x=100 开始,左侧延伸 30,50,70,右侧延伸 100+ 值

标签: r plot bar-chart


【解决方案1】:

试试下面的例子:

#data
x <- c(30,50,70,120,150)

#if less than 100 then plot to the left, ie: negaitve.
plot_x <- ifelse(x<100,x*-1,x)

#plot no x axis
barplot(plot_x,horiz=T,axes = FALSE,xlim=c(-200,200))

#add x and y axis
axis(1,at=seq(-100,100,50),
     labels = seq(0,200,50))
axis(2,pos=0)

【讨论】:

    【解决方案2】:

    ggplot 解决方案:

    x <- c(30,50,70,120,150)
    x_100 <- data.frame(x=seq_along(x),y=x-100)
    y_br <- seq(-75,50,25)
    
    ggplot(x_100,aes(x=x,y=y)) + geom_bar(stat="identity") + 
       coord_flip() + scale_y_continuous(breaks=y_br,labels=y_br+100)
    

    数据必须转到ggplot 的数据框。我从数据中减去 100,然后使用 scale_y_continuous 将标签放回“原始”值。

    ggplot 中,条形图是用竖线绘制的。 coord_flip 用于交换 x 轴和 y 轴,从而导致水平条。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多