【问题标题】:scaling x and y axis (geom_bar)缩放 x 和 y 轴 (geom_bar)
【发布时间】:2019-10-25 22:14:21
【问题描述】:

我在绘制看似简单的情节时遇到了麻烦。

x <-
  read_excel("Desktop/Book1.xlsx",
             col_types = c("numeric", "numeric", "numeric"))

x1 <-  gather(hospitals, key = "sector", value = "count", 2:3)



p <- ggplot(data = x1, aes( x = Years, y = count, fill = sector )) +
  geom_col(position="stack", stat="identity", width = 5, colour="black") +
  geom_text(aes(label=count), vjust=1, color="white", size=2) +
  guides(fill=FALSE)+
  scale_fill_grey() +
  theme_bw(base_size = 12 )

p


data is 

1   1946    Public hospitals    35
2   1984    Public hospitals    41
3   2000    Public hospitals    65
4   2001    Public hospitals    67
5   2002    Public hospitals    66
6   2003    Public hospitals    76
7   2004    Public hospitals    77
8   2005    Public hospitals    85
9   2006    Public hospitals    90
10  2007    Public hospitals    94
11  2008    Public hospitals    97
12  2009    Public hospitals    102
13  2010    Public hospitals    102
14  1946    Private hospitals   NA
15  1984    Private hospitals   139
16  2000    Private hospitals   325
17  2001    Private hospitals   336
18  2002    Private hospitals   343
19  2003    Private hospitals   364
20  2004    Private hospitals   376
21  2005    Private hospitals   376
22  2006    Private hospitals   353
23  2007    Private hospitals   355
24  2008    Private hospitals   365
25  2009    Private hospitals   370
26  2010    Private hospitals   376
Showing 12 to 26 of 26 entries, 3 total columns  

我以这个结果结束!

首先,如何修改 x 轴以显示分隔的条形并且仅在我有数据的年份? [可以省略 1960 年左右的 x 轴并挤压条形以节省空间吗? 第二,如何固定Y轴?有些条形比它们的价值高!

【问题讨论】:

  • 你能举一个比他们的价值更高的酒吧的例子吗?条形图是堆叠的,所以我希望总高度是给定年份两个部门值的总和。

标签: r ggplot2 graph


【解决方案1】:
x1 %>%
  ggplot(aes( x = as.character(Years), y = count, fill = sector )) +
  geom_col(position="stack", colour="black") +
  geom_text(aes(label=count), vjust=1, size=2,
            color=ifelse(df$sector != "Public hospitals", "white", "black")) +
  guides(fill=FALSE) +
  scale_x_discrete(name = "Year") +
  scale_fill_grey() +
  theme_bw(base_size = 12)

编辑:经过重新考虑,我意识到我没有正确堆叠文本的位置。这些数据恰好看起来不错,但这只是巧合。为了获得文本的正确定位,一种方法是手动:我们可以总结每年的累积高度:

x1 %>%
  group_by(Years) %>%
  mutate(cuml_count = cumsum(count)) %>%
  ungroup() %>% ....

geom_text(aes(label = count, y = cuml_count), vjust = 1, size = 2,
          color=ifelse(df$sector != "Public hospitals", "white", "black")) +

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2016-02-14
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多