反向创建水平条形图 [英] Creating a horizontal bar plots in the reverse direction

查看:139
本文介绍了反向创建水平条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中做一个金字塔形的像"图,我想我已经接近了.我知道有一些功能,例如plotrix的 pyramid.plot ,但是我想做的不是一个真正的金字塔图.在金字塔图中,中间的文本标签与左侧和右侧的条对齐.相反,我想做的是两列文本,其中有条形图离开它们.

I'm trying to do a pyramid-"like" plot in R and I think I am close. I know there are functions such as plotrix's pyramid.plot but what I want to do isn't a real pyramid plot. In a pyramid plot, there are text labels down the middle that line up with the bars on the left and on the right. Instead, what I'd like to do is have two columns of text with bars coming away from them.

我正在使用ggplot(但我想不必这样做)和

I'm using ggplot (but I guess I don't have to) and the multiplot function. A minimal example would be something like this:

mtcars$`car name` <- rownames(mtcars)
obj_a <- ggplot (mtcars, aes (x=`car name`, y=mpg))
obj_a <- obj_a + geom_bar (position = position_dodge(), stat="identity")
obj_a <- obj_a + coord_flip () 
obj_a <- obj_a + xlab ("")

USArrests$`states` <- rownames(USArrests)
obj_b <- ggplot (USArrests, aes (x=`states`, y=UrbanPop))
obj_b <- obj_b + geom_bar (position = position_dodge(), stat="identity")
obj_b <- obj_b + coord_flip () 
obj_b <- obj_b + xlab ("")

multiplot (obj_a, obj_b, cols=2)

看起来像这样:

我想我只是想翻转左半部分,以便每一行都有(从左到右):左栏,汽车型号,州名,右栏. (我正在制作的图形在两半中将具有相同的行数,因此不会显得局促.)但是,重点是,文本有两列,而不是一列.

I guess what I'd like is just to flip the left half so that each row has (from left-to-right): left bar, car model, state name, right bar. (The graph I'm making will have the same number of rows in both halves so it won't look so cramped.) However, the point is, there are two columns of text, not one.

当然,由于两个半部彼此独立,所以我真正的问题是我不知道该怎么做左半部. (一个条形图,条形图的方向相反.)但是我想我也要解释一下我想做的事情...

Of course, since both halves are independent of each other, my real problem is I don't know how to make the left half. (A bar plot with bars going in the opposite direction.) But I thought I'd also explain what I'm trying to do...

提前谢谢!

推荐答案

您可以将mpg值设置为obj_a否,&将汽车名称轴放置在另一侧:

You can set the mpg values in obj_a negative, & position the car names axis on the opposite side:

ggplot (mtcars, aes (x=`car name`, y=-mpg)) +         # y takes on negative values
  geom_bar (position = position_dodge(), stat = "identity") + 
  coord_flip () + 
  scale_x_discrete(name = "", position = "top") +     # x axis (before coord_flip) on opposite side
  scale_y_continuous(name = "mpg",
                     breaks = seq(0, -30, by = -10),  # y axis values (before coord_flip) 
                     labels = seq(0,  30, by =  10))  # show non-negative values

这篇关于反向创建水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆