在条形图上绘制标签,位置="填充"在R ggplot2中

时间:2016-11-16 00:16:45

标签: r plot ggplot2 bar-chart

如何绘制一个情节"填充"使用ggplot2计算标签的栏?

我能够为#34;堆叠"酒吧。但是,我非常困惑。

以下是使用 dplyr mpg 数据集

的可重现示例
library(ggplot)
library(dplyr)

mpg_summ <- mpg %>%
  group_by(class, drv) %>%
  summarise(freq = n()) %>%
  ungroup() %>%
  mutate(total = sum(freq), 
         prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv)) +
  geom_text(aes(label = freq), position = position_stack(vjust = .5))

enter image description here

但是,如果我尝试绘制填充条的计数,它就不起作用

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + stat_count(aes(y = (..count..)/sum(..count..)), geom="bar", position="fill")  +
  scale_y_continuous(labels = percent_format())

enter image description here

此外,如果我尝试:

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + geom_bar(aes(y = freq), position="fill")  +
  geom_text(aes(label = freq), position = "fill") +
  scale_y_continuous(labels = percent_format())

我明白了:

Error: stat_count() must not be used with a y aesthetic.

1 个答案:

答案 0 :(得分:3)

我错过了上一个问题的填充部分。这应该可以帮助你:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up) do |user_params|
            user_params.permit({ roles: [] }, :email, :password, :password_confirmation)
      end
  end
end  

enter image description here