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

Friday, April 22, 2022

[FIXED] How to make faceted pie charts for a dataframe of percentages in R?

 April 22, 2022     facet-wrap, ggplot2, melt, pie-chart, r     No comments   

Issue

I have reached to create a melted dataframe containing as values the % of the energy sources (factor variable) for several Years, as additional factor or Date: enter image description here

How could I make nice faceted pie charts for the different years with ggplot (or plotrix)?

So, far, I have reached to:

ggplot(melted_df, aes(x=Year, y=Share, fill=Source)) +
  geom_bar(stat="identity", width=1)+
  coord_polar("y", start=0) +
  geom_text(aes(label = paste0(round(Share*100), "%")), position = position_stack(vjust = 0.5),size=3)+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
          axis.text = element_blank(),
          axis.ticks = element_blank(),
          plot.title = element_text(hjust = 0.5, color = "#666666"))

which without the facet command gives this, which is not aesthetically pleasant: enter image description here

while if I add the facet_wrap(~Year) command, it becomes worse... enter image description here


Solution

After commentators suggestion, aes(x=1) in the ggplot() line solves the issue and makes normal circle parallel pies:

ggplot(melted_df, aes(x=1, y=Share, fill=Source)) +
  geom_col(width=1,position="fill", color = "black")+
  coord_polar("y", start=0) +
  geom_text(aes(x = 1.7, label = paste0(round(Share*100), "%")), size=2, 
            position = position_stack(vjust = 0.5))+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
                          axis.text = element_blank(),
                          axis.ticks = element_blank(),
                          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)


Answered By - choabf
Answer Checked By - Mary Flores (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