且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ggplot2()条形图填充参数

更新时间:2021-07-11 22:45:09

只需将fill = verified添加到您的初始aes中或您的geom_bar

just add fill = verified to your initial aes or within your geom_bar

# common elements
g_df <- df %>%
  count(procedure, verified) %>%
  mutate(prop = round((n / sum(n)) * 100), 2) %>%
  group_by(procedure)

# fill added to initial aes
g1 <- ggplot(g_df, aes(x = procedure, y = prop, fill = verified)) +
  geom_bar(stat = "identity", colour = "black")

# fill added to geom_bar
g2 <- ggplot(aes(x = procedure, y = prop)) +
  geom_bar(aes(fill = verified), stat = "identity", colour = "black")

g1g2都在下面产生相同的图

Both g1 and g2 produce the same plot below

正如 eipi10 在对我的答案的评论中所建议的那样,您可以通过将xaxis设置为factor(以下代码的修改)来清理xaxis.

As suggested by eipi10 in the comments to my answer, you could clean up the xaxis by making it a factor, a modification of their code below.

df %>%
  count(procedure, verified) %>%
  mutate(prop = n / sum(n)) %>%
  ggplot(aes(x = factor(procedure), y = prop, fill = verified)) +
  geom_bar(stat = "identity", colour = "black") +
  labs(x = "procedure", y = "percent")

生产