Home > Blockchain >  ggplot unable to fill plot by dataframe variable
ggplot unable to fill plot by dataframe variable

Time:01-31

I am attempting to plot a dataset and have the points filled dependent on a variable within the dataset; however, I am not getting the results I expected with the following code:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
library(RColorBrewer)
#> Warning: package 'RColorBrewer' was built under R version 4.0.3
df <- data.frame(
         ID   = c("B2008","0E00A", "24101"),
         Rate = c(0.12016, 0.12528, 0.24614),
         Pos  = c(0.0796, 0.0849, 0.18316),
         Neg  = c(0.0249, 0.0249, 0.0925),
         Ret  = c(0.0547, 0.06, 0.09066),
         EmpCategory = c("Full-Time", "Part-Time", "Un-Employed")
      )


head(df, 2)
#>      ID    Rate    Pos    Neg    Ret EmpCategory
#> 1 B2008 0.12016 0.0796 0.0249 0.0547   Full-Time
#> 2 0E00A 0.12528 0.0849 0.0249 0.0600   Part-Time

## Plot Rate vs Return, filled by Employee Category, sized by Negative (Losses)
ggplot(df)  
    aes(x=Rate,y=Ret,fill=EmpCategory,size=Neg)  
    geom_point()  
    xlab("Rate")  
    ylab("Return")  
    scale_fill_brewer(palette='RdYlGn')


## Plot Rate vs Return, filled by Positive (gains), sized by Employee Category
ggplot(df)  
    aes(x=Rate,y=Ret,fill=Pos,size=EmpCategory)  
    geom_point()  
    xlab("Rate")  
    ylab("Return")  
    scale_fill_distiller(palette='RdYlGn')
#> Warning: Using size for a discrete variable is not advised.

First ggplot call produces this plot.
Second ggplot call produces this plot.

As you can see, regardless of whether I use a categorical or continuous variable, it doesn't seem that I can fill the color of the points by variable. Any and all insight into what I am doing incorrectly would be greatly appreciated.

CodePudding user response:

Use color = EmpCategory instead of fill.

More about color related aes here: https://ggplot2.tidyverse.org/reference/aes_colour_fill_alpha.html

  •  Tags:  
  • Related