从不等于 0 的 x 轴开始绘制条形图并向两侧延伸
Plot bars starting from x axis not equal to 0 and extend to both sides
假设我的数据值为
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+ 个值
试试下面的例子:
#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)
一个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
将标签放回 "original" 值。
在ggplot
中,条形图是用垂直条绘制的。 coord_flip
用于互换 x 轴和 y 轴,从而产生水平条。
假设我的数据值为
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+ 个值
试试下面的例子:
#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)
一个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
将标签放回 "original" 值。
在ggplot
中,条形图是用垂直条绘制的。 coord_flip
用于互换 x 轴和 y 轴,从而产生水平条。