![](/img/trans.png)
[英]How to customise axes labels in ggplot2 from a list of string inputs?
[英]How to represent bipolar survey question in ggplot2 with multiple axes labels
我有一个格式问题的调查数据
| Statement A | Agree strongly w/ A| ... | Agree strongly w/ B | Statement B |
| A1 | o | ... | o | B1 |
我想用条形图显示每条语句的均值,在条形图的两边都带有标签-语句A的左侧是标签,语句B的右侧是标签,如下所示:
(来源: tomvladeck.com )
我想在标签“ Statement A”和“ Statement B”下看到y轴线,在方框“ A1”,“ A2”和“ B1”下看到y轴标签, B2”。 在使用ggplot
时,使用scale_y_discrete
只能有一条线(据我所知),并且可以使用position = "right"
将其移到position = "right"
,但是afaik不能有两条轴线(即使它们是相同的比例)。
这没有多个y
缩放,我知道ggplot2
本身不支持。 从技术上讲,它具有一个离散的y比例,但是具有两组标签,但是除了使用大量的annotates
,我不知道如何在ggplot2
实现此功能。 这里有什么帮助吗? 这可以在自然ggplot中完成吗?
这是最低限度的建议:
example_df <-
data.frame(
statement_a = c("I like to take risks",
"I work to provide for my family"),
statement_b = c("I am more risk averse",
"I work to provide for myself"),
value = c(-1.5, .5)
)
plot_1 <-
ggplot(example_df,
aes(x = statement_a, y = value)) +
geom_col() +
coord_flip() +
scale_x_discrete(name = "")
plot_2 <-
ggplot(example_df,
aes(x = statement_b, y = value)) +
geom_col() +
coord_flip() +
scale_x_discrete(name = "", position = "top")
情节A看起来像这样:
(来源: tomvladeck.com )
图B如下所示:
(来源: tomvladeck.com )
想法是显示两条轴线(A处的左侧,B处的右侧)
ggplot
不支持多个y轴(除非它们都是数字且一个是另一个的小数位)。 有很多与此相关的帖子,您可以自己搜索。 这是一种变通方法,可以为您解决问题。
example_df <-
data.frame(
statement_a = c("I like to take risks",
"I work to provide for my family"),
statement_b = c("I am more risk averse",
"I work to provide for myself"),
value = c(-1.5, .5)
)
row_count <- nrow(example_df)
max_value <- max(abs(example_df$value))
example_df$y <- 1:row_count
library(ggplot2)
ggplot(example_df) +
geom_rect(aes(xmin = rep(0, row_count),
xmax = value,
ymin = y-0.3, ymax = y+0.3)) +
geom_text(aes(x = -max_value-0.2,
y = y,
label = statement_a),
hjust = 1) +
geom_text(aes(x = max_value-0.2,
y = y,
label = statement_b),
hjust = 0) +
xlim(c(-max_value-10,max_value+10)) +
theme_void()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.