r - 缩放 x 和 y 轴 (geom_bar)
问题描述
我在绘制看似简单的情节时遇到了麻烦。
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轴?有些酒吧比他们的价值更高!
解决方案
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")) +
推荐阅读
- winapi - 解决 Visual Studio Code 中 Python 脚本自动调试的错误
- java - 链表 - 以 K 组反转链表
- javascript - 使用递归转换对象数据
- angular - 定义自定义typings.d.ts并不能解决导入js库的问题
- python-3.x - Python tkinter 如何将信息从 Text 小部件复制到 Canvas 小部件?
- c - Realloc 返回 NULL,但不设置 errno。如何正确检查此错误/奇怪行为?
- python - Postgres ON CONFLICT DO NOTHING 查询
- python - 变量只存储一个值,python
- c++ - 使用外部 txt 文件验证密码不起作用
- html - 锚元素有效,但 Blazor 客户端中的按钮无效