【问题标题】:Custom x-label for ordered stacked bar graph in R ggplot2 [duplicate]R ggplot2中有序堆叠条形图的自定义x标签[重复]
【发布时间】:2017-08-15 16:30:28
【问题描述】:

我正在尝试为 ggplot2 中的有序堆叠条形图创建自定义标签。

我的花园里有六种不同的动物——海狸、大象、袋鼠、老鼠、龙和吉娃娃。

我两次让他们每人为我唱歌,一次是在他们开心的时候,一次是在他们悲伤的时候。我记录了他们每次唱歌的时长。

我想在堆积条形图中绘制动物的总歌唱时间,一个堆积条对应一只动物,堆积条的每个组成部分对应动物的情绪,但我想按照堆积条的顺序排列堆积条动物的大小,动物的名字显示在条形下方。

为了做到这一点,我在数据框中创建了一个列,将尺寸顺序信息与动物因素(例如“1.mouse”等)结合起来。这允许条形按大小顺序显示。然后我尝试使用“子字符串”来提取与 x 标签名称相对应的字母(以便它读取例如“鼠标”等),但没有成功。

如果我只使用“动物”来标记轴,那么 ggplot 会使用按字母顺序列出的动物名称来标记条形。我也尝试过使用“订单”功能。

我查看了堆栈溢出和其他网站,但在其他地方找不到确切的问题。

非常感谢我和我的动物园!

animal<-rep(c("beaver","elephant","kangaroo","mouse","dragon","chihuahua"),2)
size_order<-rep(c(3,5,4,1,6,2),2)
mood<-c((rep("happy",6)),rep("sad",6))
singing_time<-as.numeric(rnorm(12, 5, 2))
ordered_animal<-paste(size_order,animal,sep = ".")

singing_data<-as.data.frame(cbind(mood,singing_time,ordered_animal))

ggplot(singing_data, aes(x = ordered_animal, y = singing_time, fill = mood, label = singing_time)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = levels(substring(as.factor(ordered_animal),3,10)))

【问题讨论】:

标签: r ggplot2 axis-labels stacked-chart stackedbarseries


【解决方案1】:

部分问题在于您对cbind 的使用将不同的数据类型(数字、因子)强制转换为单一数据类型(数字)的矩阵。尝试带有向量参数的 data.frame 构造函数。

您不需要将数字放入因子水平,也不需要“有序因子”(这对回归和其他建模很有用,但这里不需要)。只需使用带有 levels= 的常规因子即可处理显示顺序。

您的另一个问题是您的动物尺寸顺序不正确,因此示例结果看起来不正确。

animal_items <- c("beaver","elephant","kangaroo","mouse","dragon","chihuahua")
corrected_size_order<-c(4,6,1,3,2,5) # applies to animal_items

animal<-rep(animal_items,2)
ordered_animal <- factor(animal, levels=animal[corrected_size_order])

mood<-c((rep("happy",6)),rep("sad",6))
singing_time<-as.numeric(rnorm(12, 5, 2))

singing_data<-data.frame(mood,singing_time,ordered_animal)

ggplot(singing_data, aes(x = ordered_animal, y = singing_time, fill = mood, label = singing_time)) +
  geom_bar(stat = "identity")

【讨论】:

  • 谢谢你。看起来levels=会处理它。我让事情变得比他们需要的更复杂。我会用我的其他数据来试试这个。我不确定我是否理解您的更正尺寸顺序(4、6、1、3、2、5)与下图中的数据(这是我想到的正确尺寸顺序)如何对应,但我会尝试我自己。
  • @Ian mouse(动物物品中的第 4 个元素)是最小的。所以大小顺序的第一个元素是 4。龙(动物物品的第 5 个元素)是最大的。所以大小顺序的最后一个元素是5。等等。
  • 啊,好的。工作方式与我的想法完全不同。再次感谢,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 2014-08-30
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多