首页 > 解决方案 > 更改 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这里应用。

标签: rggplot2

解决方案


我已经生成了一些示例数据......希望我已经正确理解了情况。这似乎有效,即使用指定的标签在条形图的指定位置插入中断。

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'))

推荐阅读