将ggplot轴重新排列一个值,从另一个显示标签

问题描述 投票:0回答:1

情况如下:对于这些名称,我有很多名称和许多相应的代码。所有不同的名称都有唯一的代码,但并非所有不同的代码都具有唯一的名称。

这在绘制数据时产生了一个问题,因为我需要group_by(code),在绘制时却需要reorder(name,code),但是代码是胡说八道,我想显示名称。由于某些代码共享名称,因此会产生一些问题。

示例如下:

library(tidyverse)
set.seed(1)

# example df
df <- tibble("name" = c('apple','apple','pear','pear','pear',
                        'orange','banana','peach','pie','soda',
                        'pie','tie','beer','picnic','cigar'),
             "code" = seq(1,15),
             "value" = round(runif(15,0,100)))
df %>% 
  ggplot(aes(x=reorder(name,value)))+
  geom_bar(aes(y=value),
           stat='identity')+
  coord_flip()+
  ggtitle("The axis labels I want, but the order I don't")

plot example 1

df %>% 
  ggplot(aes(x=reorder(code,value)))+
  geom_bar(aes(y=value),
           stat='identity')+
  coord_flip()+
  ggtitle("The order I want, but the axis labels I don't")

enter image description here


不太确定如何获取ggplot来保持第二个图的显示和顺序,同时能够用第一个图的名称替换轴标签。

r ggplot2 geom-bar
1个回答
0
投票

关于使用interaction绑定名称和代码,并在scale_x_discrete中用适当的标签替换标签,例如:

df %>% 
  ggplot(aes(x=interaction(reorder(name, value),reorder(code,value))))+
  geom_bar(aes(y=value),
             stat='identity')+
  scale_x_discrete(labels = function(x) sub("\\..*$","",x), name = "name")+
  coord_flip()

enter image description here

这是您要寻找的吗?

© www.soinside.com 2019 - 2024. All rights reserved.