英文:
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
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'))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论