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

Friday, April 22, 2022

[FIXED] Why pies are flat in geom_scatterpie in R?

 April 22, 2022     pie-chart, r, scatterpie     No comments   

Issue

Why are the pies flat?

    df<- data.frame(
      Day=(1:6),
      Var1=c(172,186,191,201,205,208),
      Var2= c(109,483,64010,161992,801775,2505264), A=c(10,2,3,4.5,16.5,39.6), B=c(10,3,0,1.4,4.8,11.9), C=c(2,5,2,0.1,0.5,1.2), D=c(0,0,0,0,0.1,0.2))

ggplot() + 
  geom_scatterpie(data = df, aes(x = Var1 , y = Var2, group = Var1), cols = c("A", "B", "C", "D")) 

enter image description here

I have tried using coord_fixed() and does not work either.

enter image description here


Solution

The problem seems to be the scales of the x- and y-axes. If you rescaled them to both to have zero mean and unit variance, the plot works. So, one thing you could do is plot the rescaled values, but transform the labels back into the original scale. To do this, you would have to do the following:

Make the data:

df<- data.frame(
    Day=(1:6),
    Var1=c(172,186,191,201,205,208),
    Var2= c(109,483,64010,161992,801775,2505264), A=c(10,2,3,4.5,16.5,39.6), B=c(10,3,0,1.4,4.8,11.9), C=c(2,5,2,0.1,0.5,1.2), D=c(0,0,0,0,0.1,0.2))

Rescale the variables

df <- df %>% 
    mutate(x = c(scale(Var1)), 
           y = c(scale(Var2)))

Find the linear map that transforms the rescaled values back into their original values. Then, you can use the coefficients from the model to make a function that will transform the rescaled values back into the original ones.

m1 <- lm(Var1 ~ x, data=df)
m2 <- lm(Var2 ~ y, data=df)
trans_x <- function(x)round(coef(m1)[1] + coef(m1)[2]*x)
trans_y <- function(x)round(coef(m2)[1] + coef(m2)[2]*x)

Make the plot, using the transformation functions as the call to labels in the scale_[xy]_continuous() functions

ggplot() + 
    geom_scatterpie(data=df, aes(x = x, y=y), cols = c("A", "B", "C", "D")) + 
    scale_x_continuous(labels = trans_x) + 
    scale_y_continuous(labels = trans_y) + 
    coord_fixed() 

enter image description here

There may be an easier way than this, but it wasn't apparent to me.



Answered By - DaveArmstrong
Answer Checked By - Robin (PHPFixing Admin)
  • 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