PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

[FIXED] How to create two pie charts using a split condition?

 April 23, 2022     pie-chart, r     No comments   

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

enter image description here


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()

enter image description here


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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing