如何为ggplot的aes使用数据框的名称和rownames?

Nie*_*ein 10 r ggplot2

我有一个enrichment_df看起来像这样的数据框

                                         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
Run Code Online (Sandbox Code Playgroud)

我想用/sf/answers/1625979141/中的示例制作一个重叠的条形图.我希望填充为rownames,x轴为colnames.我尝试绘制它

ggplot(enrichment_df, aes_string(names(enrichment_df), fill = rownames(enrichment_df))) + 
geom_bar(position = 'identity', alpha = .3)
Run Code Online (Sandbox Code Playgroud)

但是,这会给出错误 object 'day1_day3__sham3_strict_enrichment' not found

如何在ggplot的aes(或aes_string)中使用rownames和colnames?

Bea*_*eld 17

无论何时使用,ggplot您都应该使用长格式的数据:

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
Run Code Online (Sandbox Code Playgroud)

这可以通过绘制

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

在此输入图像描述

我不确定position = "identity"你是否正在寻找负值.