[英]scaling x and y axis (geom_bar)
我在繪制看似簡單的 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
首先,如何修改 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")) +
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.