r - R 中的绘图因子比例

标签 r plot ggplot2

我有一个如下所示的数据集:

     edu   default 
1    1      0    
2    3      1    
3    1      1   
4    1      0   
5    2      1   
6    2      0   
...

我可以使用 R 绘制一个图:

ggplot(rawdata, aes(x = edu, fill = default)) +
  geom_bar() +
  labs(x = 'Education') +
  theme_excel()

enter image description here

我想绘制1的比例,而不是默认中的10计数>像这样:

enter image description here

我单独计算了比例,将结果存储在另一个数据框中并绘制了此图。

我的问题是:是否有一种紧凑的方式可以在一个 ggplot() 中完成此操作像我在上一个图中所做的那样命令?

更新: 我忘了说 default 的数据类型是因素。所以申请mean不起作用。

最佳答案

我们记得二进制向量中 1 的比例就是它的平均值。在 ggplot 中绘制每个 x 平均值的方法是使用 stat_summary 函数。所以我们得到:

ggplot(rawdata, aes(x = edu, y = default)) + 
  stat_summary(fun.y = 'mean', geom = 'bar')

或者:

ggplot(rawdata, aes(x = edu, y = default)) + 
    geom_bar(stat = 'summary')               #include fun.y = 'mean' to avoid the message

两者都给出:

enter image description here

关于r - R 中的绘图因子比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943657/

相关文章:

r - 为什么调用 `detach` 会导致 R 调用 "forget"函数?

r - 在 ggplot 中对齐和排列图表

R kmeans (stats) vs Kmeans (amap)

r - xgboost : need label when data is a matrix

r - R中Barplot中的X轴

r - 在 R 中绘制跨多个级别的二进制频率

javascript - 是否可以在plotly.js箱形图上叠加标记?

r - 如何在不创建摘要数据框的情况下在 ggplot2 中标记堆积条形图?

r - 如何阻止ggrepel标签在R/ggplot2中的gganimate帧之间移动?

r - 如何从字符向量 : the object names as the vector element names, 创建多个对象并将对象值作为向量元素值