Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use names and rownames of a dataframe for the aes of ggplot?

Tags:

r

ggplot2

I have a dataframe enrichment_df that looks like this

                                         meclocycline pimozide isocorydine alvespimycin
day1_day3__sham3_strict_enrichment             -0.869    0.855      -0.859        0.539
hour4_day1_day3__sham3_strict_enrichment       -0.294    0.268      -0.539       -0.120
day7_day14__sham3_strict_enrichment            -0.333    0.404       0.297        0.233
day90__sham3_strict_enrichment                 -0.511   -0.657      -0.519        0.184
day14__sham3_strict_enrichment                 -0.239   -0.420       0.513       -0.422
day7__sham3_strict_enrichment                  -0.394   -0.380      -0.408        0.337

and I want to make an overlapping barplot with the example from https://stackoverflow.com/a/23228273/651779. I want the fill to be the rownames, and the x-axis the colnames. I try to plot it with

ggplot(enrichment_df, aes_string(names(enrichment_df), fill = rownames(enrichment_df))) + 
geom_bar(position = 'identity', alpha = .3)

However, this gives the error object 'day1_day3__sham3_strict_enrichment' not found

How can I use the rownames and colnames in the aes (or aes_string) of ggplot?

like image 563
Niek de Klein Avatar asked Apr 23 '14 13:04

Niek de Klein


1 Answers

Whenever using ggplot you should have your data in long format:

enrichment_df[ "day" ] <- rownames(enrichment_df)
df.molten <- melt( enrichment_df, id.vars="day", value.name="Enrichment", variable.name="Antibiotics" )

head(df.molten)
                                       day  Antibiotics Enrichment
1       day1_day3__sham3_strict_enrichment meclocycline     -0.869
2 hour4_day1_day3__sham3_strict_enrichment meclocycline     -0.294
3      day7_day14__sham3_strict_enrichment meclocycline     -0.333

This can be plotted by

ggplot(df.molten, aes( x = Antibiotics, y = Enrichment, fill = day ) ) + 
  geom_bar( position = "identity", stat = "identity", alpha = .3 )

enter image description here

I'm not sure though if position = "identity" with negative values is what you are looking for.

like image 124
Beasterfield Avatar answered Oct 04 '22 04:10

Beasterfield