【问题标题】:Graph bars only appear when lower limit of y axis set to 0 in ggplot图表条仅在 ggplot 中 y 轴的下限设置为 0 时出现
【发布时间】:2021-02-03 01:48:53
【问题描述】:

我正在尝试创建条形图。当我将限制设置为 (0,7) 时,会出现条形。但是,我希望下限为 1,而不是 0。当我将下限设置为 1 时,条形不会出现。我收到以下错误消息:

Removed 8 rows containing missing values (geom_bar).

我如何设置限制并不重要。我使用了以下两个选项:

ylim(1, 7)

scale_y_continuous(limits = c(1, 7))

有谁知道我该如何解决这个问题?

我想要一个看起来像这样的图表,但将 1 作为较低的 y 轴标签,这意味着所有条形都将向下移动 1。

这是图表的完整代码:

full %>%
 ggplot(aes(x = order, y = mean)) + 
 geom_bar(stat = "identity", fill = "003900", width = 0.5, position = position_dodge()) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) +
  geom_text(aes(label = round(mean, digits =1)), position = position_dodge(width=1.0), vjust = -4.0, size = 3) +
  #facet_wrap(~names) +
  labs(title = "Behavioral intentions in response to each message") +
 # ylim(0, 7) + 
  scale_y_continuous(limits = c(1, 7)) + 
  theme(axis.text = element_text(size = 7)) + 
  xlab("Message") + 
  ylab("Behavioral intentions")

这是可重复的数据:

structure(list(message = c("a", "e", "h", "m", "convince_animals", 
"convince_environment", "convince_health", "convince_money"), 
    mean = c(3.1038961038961, 3.21052631578947, 3.56, 2.7972972972973, 
    4.19512195121951, 4.18536585365854, 5.65365853658537, 4.93658536585366
    ), se = c(0.208814981196227, 0.204609846510406, 0.220760356801522, 
    0.20542415978608, 0.121188432228325, 0.11075110910238, 0.0896896391724367, 
    0.120394657272105), type = c("Behavioral Intentions", "Behavioral Intentions", 
    "Behavioral Intentions", "Behavioral Intentions", "Expected Behavior", 
    "Expected Behavior", "Expected Behavior", "Expected Behavior"
    ), names = c("Animals", "Environment", "Health", "Money", 
    "Animals", "Environment", "Health", "Money"), order = c(1, 
    3, 5, 7, 2, 4, 6, 8)), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

标签: r ggplot2 graph bar-chart


【解决方案1】:

看起来您通过设置限制丢失了数据,并且搞砸了您的情节。您可以使用coord_cartesian() 而不是ylim() 来“放大”您的数据;请参阅https://stackoverflow.com/a/25685952/12957340 和/或ggplot2 book 的第 160 页了解更多信息。

full %>%
  ggplot(aes(x = order, y = mean)) + 
  geom_bar(stat = "identity", fill = "003900", width = 0.5, position = position_dodge()) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) +
  geom_text(aes(label = round(mean, digits =1)), position = position_dodge(width=1.0), vjust = -4.0, size = 3) +
  #facet_wrap(~names) +
  labs(title = "Behavioral intentions in response to each message") +
  coord_cartesian(ylim = c(1, 7)) + 
  theme(axis.text = element_text(size = 7)) + 
  xlab("Message") + 
  ylab("Behavioral intentions")

【讨论】:

  • 我查看了您发布的资源,但我仍然想不出一种方法来做到这一点,看起来图表在底部被切断了。我已经编辑了我的问题,以便更清楚地了解我要完成的工作。
猜你喜欢
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多