繁体   English   中英

ggplot2 定制叠条 plot

[英]ggplot2 custom stacked bar plot

我使用一个数据集来拟合三种模型,并应用分解来计算每个变量的特征重要性。 我想像下面的示例一样可视化结果,以在三个模型之间进行比较。 是否可以绘制具有给定 y 和分解结果的堆叠条 plot?

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity))

在此处输入图像描述

这是我的数据示例:

tibble(
  methods = c("linear regression", "decision tree", "random forest"), 
  y  = c(1, 2, 3), 
  g1 = c(0.3, 0.8, 1.3), 
  g2 = c(0.5, 1,   1), 
  g3 = c(0.2, 0.2, 0.7)
)

# A tibble: 3 × 5
  methods               y    g1    g2    g3
  <chr>             <dbl> <dbl> <dbl> <dbl>
1 linear regression     1   0.3   0.5   0.2
2 decision tree         2   0.8   1     0.2
3 random forest         3   1.3   1     0.7

感谢 MeisamYSF 的回答! plot 可以

library("reshape2")

df <- tibble(
  methods = c("linear regression", "decision tree", "random forest"), 
  y  = c(1, 2, 3), 
  g1 = c(0.3, 0.8, 1.3), 
  g2 = c(0.5, 1,   1), 
  g3 = c(0.2, 0.2, 0.7)
)
df <- df %>% select(-y)

df_melt <- melt(df, id.vars = 'methods')
ggplot(df_melt, aes(x=methods, y=value, fill=variable)) + 
  geom_bar(position="stack", stat="identity")

在此处输入图像描述

您可以使用来自reshape2 package 的melt function 来将您的小标题融化成一种格式,其中每一行都是一个唯一的 id 变量条目:

library(reshape2);
library(ggplot2);
df_melt <- melt(df, id.vars = 'methods')
ggplot(df_melt, aes(x=methods, y=value, fill=variable)) + geom_bar(position="fill", stat="identity")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM