问题
I have some major problems with ggplot2. Even though it might be a very easy question to you I couldnt manage yet to get it right (I have read a ggplot2-book and was looking on stackoverflow as well).
Orginally there was a dataset consisting of a factor variable (country) and a dichotomous variable. Unfortunately I dont have my data in this extended format myself: I have two variables "var1" and "var2". var1 gives the number of cases in the original dataset where a certain condition is true and var2 gives the number of cases where the same condition is false:
country | var1 | var2
----------------------
"A" | 20 | 30
"B" | 24 | 53
"C" | 21 | 24
"D" | 30 | 66
Now I'd like to produce a stacked barplot with a y-axis showing percentages within each country (all bars should have the same height) plus the absolute numbers displayed within the bars:
How it should look
I found out that if the data were in an extended format, I could use
ggplot(data=dataset)+geom_bar(aes(x=country, fill=variable), position='fill')
However, I only have aggregated data.
Could anyone please help me?
Thank you!
回答1:
A quick solution by first reshaping and then plotting:
library(ggplot2)
library(tidyr)
temp2 <- gather(temp, var, val, -country)
ggplot(temp2, aes(country, val, fill = var)) +
geom_col(position = 'fill') +
geom_text(aes(label = val), position = position_fill(vjust = 0.5)) +
scale_y_continuous(labels = scales::percent_format())
回答2:
library('ggplot2')
library('data.table')
df1 <- fread('country var1 var2
"A" 20 30
"B" 24 53
"C" 21 24
"D" 30 66')
df1 <- melt(df1, id.vars = 'country', )
df1[, percent := prop.table(value)*100, by = 'country']
ggplot(data = df1, aes( x = country, y = percent, fill = variable, label = value )) +
geom_bar(stat = 'identity') +
geom_text(size = 5, position = position_stack(vjust = 0.5))
来源:https://stackoverflow.com/questions/42780856/stacked-barplot-with-aggregated-data-ggplot2