我在绘制看似简单的图时遇到麻烦。
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轴如何固定?一些酒吧高于他们的价值!
答案 0 :(得分:3)
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")) +