r - r 中具有主轴和辅助轴的条形图
问题描述
我有一个数据框,我想创建一个带有主轴和次轴的条形图。
geom_bar(data=top_ten_S, aes(x=Combination, y=AvgTopline), stat="identity",fill="red") +
coord_flip() +
geom_text(
data=top_ten_S,
aes(
x=Combination, y=AvgTopline,
label=paste0("R",round(AvgTopline,0)),
hjust=ifelse(AvgTopline < max(top_ten_S$AvgTopline) / 1.5, -0.1, 1.1), # <- Here lies the magic
),
)
我的df看起来像
top_ten_S <- data.frame(Combination = c("a", "b", "c"),
Nrcustomers = c(20, 200, 1900),
AvgTopline = c(1000,3000,1500))
我只能用上面的代码绘制一列 - 我想要一个辅助轴,这样我就可以针对 NrCustomers 和 AvgTopline 绘制组合
解决方案
方法一
top_ten_S %>%
gather(key, value, -Combination) %>%
ggplot(aes(x = Combination, y = value, fill = key)) +
geom_bar(stat = "identity", position = "dodge") +
labs(fill = "")
方法二
top_ten_S %>%
gather(key, value, -Combination) %>%
ggplot(aes(x = Combination, y = value, fill = key)) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
facet_grid(. ~ key)
编辑:方法2
top_ten_S %>%
gather(key, value, -Combination) %>%
ggplot(aes(x = Combination, y = value, fill = key)) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
facet_grid(. ~ key, space = "free_y", scales = "free_y") +
theme(axis.text.x = element_text(angle = 60))
推荐阅读
- android - AudioPlaybackCapture API 用于通话录音
- c# - 用 4 个算术运算符计算一个简单的语句不起作用
- javascript - Node.js 服务器未发送响应,或客户端未接收
- deep-learning - 回归器的初始化是什么?
- vb.net - 有没有一种方法可以使用 WebRequest 类在 80 以外的另一个端口上查询服务器?
- jquery - 如何让用户从下拉菜单中只选择一个选项?
- python - 将程序添加到 PATH 有什么意义?
- php - centOS 7上缺少Nginx default.conf
- javascript - 从 p:selectedCheckbox javascript 获取值复选框
- python - 计算字符串在特定列中出现的次数