Issue
I have this sample dataset:
sex Country
1 M Austria
2 F Germany
3 F Portugal
4 M Portugal
5 F France
6 M Germany
I want to create a piechart but separating and adding the data according to sex. That is, what I expect as a result is equivalent to if I wanted to separate them in a geom_bar in ggplot by the same variable. In the same visualization, but separated
From R base I do not know if there is any way to do it within the same method or I would have to separate the data previously in two tables and represent them separately
I know that using piechart is not the optimal way to represent data, but I need to do it that way for a specific request
Example of the same process but as a geom_bar
Same dataframe, but separate viz for the sex variable (colors means different countries)
Solution
with base R:
old <- par(mfrow=c(1,2))
pie(table(df$Country[df$sex == "M"]))
pie(table(df$Country[df$sex == "F"]))
par(old) # reset par
with ggplot2:
library(ggplot2)
ggplot(as.data.frame(table(df)),
aes(x = "", y = Freq, fill = Country)) +
geom_bar(stat = "identity", position = "fill") +
facet_grid(cols = vars(sex)) +
coord_polar("y", start = 0) +
theme_void()
where df
is:
df <- read.table(text = " sex Country
1 M Austria
2 F Germany
3 F Portugal
4 M Portugal
5 F France
6 M Germany", header = TRUE)
Answered By - Edo Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.