【问题标题】:Ggplot: geom_bar producing "fat" columnsGgplot:geom_bar 产生“胖”列
【发布时间】:2016-05-24 12:20:11
【问题描述】:

我有:

> myData
      esito cella
43575     R     1
42446     R     1
49653     R     1
65053     R     4
72893     R     4
58299     R     4
61609     R     4
65377     R     4
70783     R     4
71949     R     4
65939     R     4
60434     R     4

然后我想绘制它们,以便在 x 轴上获得 (1,2,3,4) 并在 y 轴上获得元素的数量。例如,因为我在位置 1 有 3 个元素,所以我想要与高度 3 的 x=1 相关的条形图等。总结一下, 我希望:

  1. x = 1 --> 高度为 3 的条形
  2. x = 2 --> 没有条形
  3. x = 3 --> 没有条形
  4. x = 4 --> 高度为 9 的条形

所以我写:

myData %>% 
  group_by(cella) %>%
  dplyr::mutate(n =n()) %>%
  unique() %>% 
  ggplot(., aes(x= cella, y=n), col="blue") + 
  geom_bar(stat='identity', fill='purple', colour="white") + #, position='dodge'
  ggtitle("Riggio rules")+
  xlab("X")+
  ylab("number")

结果:

所以我得到了两个条,但是太大了。 如果我将 + xlim(c(0, 4)) 添加到 ggplot 中,它会绘制...什么都没有!

编辑:

> dput(myData)
structure(list(esito = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L), .Label = c("B", "P", "R"), class = "factor"), 
    cella = c(1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L)), .Names = c("esito", 
"cella"), row.names = c(43575L, 42446L, 49653L, 65053L, 72893L, 
58299L, 61609L, 65377L, 70783L, 71949L, 65939L, 60434L), class = "data.frame")

【问题讨论】:

  • x 是数字还是因子?
  • 你能发布dput(myData)的输出吗?

标签: r pipe bar-chart


【解决方案1】:

您可以使用width 参数来控制肥胖。这是width = 1时的样子:

myData %>% 
     group_by(cella) %>%
     dplyr::mutate(n =n()) %>%
     unique() %>% 
     ggplot(., aes(x= cella, y=n), col="blue") + 
     geom_bar(stat='identity', fill='purple', colour="white", width = 1) + #, position='dodge'
     ggtitle("Riggio rules")+
     xlab("X")+
     ylab("number")

【讨论】:

  • 哇,你比我快了 50 秒……好建议!
  • 完美运行!我不知道为什么有时 R 试图理解我们的意图而不是做最简单的事情。无论如何,再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
相关资源
最近更新 更多