r - 更改 ggplot 中的 x 轴标签
问题描述
我有一个有 12 个 x 值的条形图。使用此代码,我得到了我想要的图,除了 x 轴标签。
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
我不想在 x 轴上显示所有 12 个值,而是想自己确定标签并且只显示 4。
我调整了这样的代码
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9)) +
scale_x_discrete( labels=c("UP\nDOWN", "DOWN\nUP", "STRAIGHT\nGAIN", "STRAIGHT\nLOSS")) +
scale_fill_discrete(name = "Trend", labels = c("negative", "flat", "positive"))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
不幸的是,我得到了 4 个标签,但也得到了 8 个 NA。我希望我的 4 个标签均匀分布在我的 x 轴上。由于我的标签是因素,我不知道如何在break
这里应用。
解决方案
我已经生成了一些示例数据......希望我已经正确理解了情况。这似乎有效,即使用指定的标签在条形图的指定位置插入中断。
library(tidyverse)
df <- tribble(~x, ~y,
'cat',10,
'dog', 20,
'rabbit', 30,
'fox', 30)
df <- df %>%
mutate(x = factor(x))
df %>% ggplot(aes(x,y))+
geom_bar(stat = 'identity') +
scale_x_discrete(breaks = c('cat','fox'), labels = c('pig', 'hen'))
推荐阅读
- bash - 用脚本覆盖文件属性
- django - Django - Ajax 表单的问题
- css - 台式机和移动设备上的负边距不一样
- chatbot - 是否可以通过 Line Messaging API 删除群聊中的消息?
- mongodb - 使用 Mongoose 连接到 docker 环境中的 MongoCryptD 实例
- node.js - 如何在MongoDB中更有效、更高效地存储数据?
- list - 重新渲染组件时如何防止自动滚动到顶部?
- clojure - 填充默认值的 ClojureScript 映射解构?
- python - 带有循环的张量流中的 tf.functon
- java - 如何在 Java 中使用来自 WSDL 文件的序列化器?