[英]scaling x and y axis (geom_bar)
I am having a trouble plotting what is seemingly simple plot.我在绘制看似简单的 plot 时遇到了麻烦。
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
and i am ending with this result!我以这个结果结束!
first, how can I modify x axis to show the bars separated and only for the years i have data for?首先,如何修改 x 轴以显示分隔的条形并且仅针对我有数据的年份? [ can the x axis around 1960 be omitted and bars squeezed to save space?
[ 可以省略 1960 年左右的 x 轴并挤压条形以节省空间吗? second, how can the Y axis be fixed?
二、Y轴怎么固定? some bars are higher than their value is!
有些酒吧比他们的价值更高!
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)
Edit: Upon reconsideration I realized I did not properly stack the positioning of the text.编辑:经过重新考虑,我意识到我没有正确堆叠文本的位置。 It happens to look ok with this data, but that's just coincidence.
这些数据恰好看起来不错,但这只是巧合。 To get the right positioning for the text, one approach is manual: we could sum up the cumulative height for each year:
为了获得文本的正确定位,一种方法是手动:我们可以总结每年的累积高度:
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")) +
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.