反转图例和数据顺序以用于geom_bar

huangapple go评论83阅读模式
英文:

Reversing legend and data order for geom_bar

问题

我已经能够创建一个如下所示的条形图:

ggplot(df, aes(x=result, y=count, fill = id)) +
  geom_bar(stat = "identity") +
  labs(x = "Example", y = "Frequency", fill = "Group") + 
  scale_x_discrete(labels = c("Positive", "Negative"))

然而,我想要将“Positive”放在左边,并且我想要将组a设置为蓝色。如果我有多个结果(例如positive,negative,unknown,small),修改后的代码会是什么样子?

英文:

I have a dataframe (df) as follows

id count result
a 3 positive
b 4 negative

I have been able to create a bar graph with this

ggplot(df, aes(x=result, y=count, fill = id)) +
  geom_bar(stat = "identity") +
  labs(x = "Example", y = "Frequency", fill = "Group") + 
  scale_x_discrete(labels = c("Positive", "Negative"))

The resulting bar graph looks like this
反转图例和数据顺序以用于geom_bar

However, I want the Positive to be on the left and i want group a to be blue. How would the modified code look like if i had multiple results (e.g., positive, negative, unknown, small)?

答案1

得分: 0

字符变量映射到ggplot中的美学元素(如x、y、fill、color等)会被转换为因子,并按因子水平的顺序排列。除非您将具有所需顺序的水平的因子传递给离散比例尺,否则它们将按字母顺序排列,因为这是创建因子时的默认行为。

因此,我们只需这样做以获得所需的顺序:

英文:

Character variables mapped to aesthetics (such as x, y, fill, color, etc) in ggplot are converted into factors, and are arranged in the order of the factor levels. Unless you pass a factor with the desired ordering of levels to the discrete scale, they will therefore be arranged alphabetically, since this is the default behaviour when factors are created.

So we simply do this to get the desired ordering:

ggplot(df, aes(factor(result, c('positive', 'negative')), count, 
               fill = factor(id, c('b', 'a')))) +
  geom_col() +
  labs(x = "Example", y = "Frequency", fill = "Group") + 
  scale_x_discrete(labels = c("Positive", "Negative")) +
  scale_fill_discrete(breaks = c('a', 'b'))

反转图例和数据顺序以用于geom_bar

huangapple
  • 本文由 发表于 2023年2月24日 01:43:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548450.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定