gpt4 book ai didi

r - 使用 ggplot2 对条形图中的条进行排序

转载 作者:行者123 更新时间:2023-12-01 14:00:00 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





ggplot legends - change labels, order and title

(1 个回答)


4年前关闭。




第一次在这里问,如果我不够清楚,请原谅我。

到目前为止,我看到很多类似问题的回复,其中解释了如何按数据框的某个字段对条形进行排序;但我一直无法找到如何通过 geom_bar 的默认统计“计数”(这显然不是数据框的字段)对它们进行排序。
例如,我运行此代码:

library(ggplot2)

Name <- c( 'Juan','Michael','Andrea','Charles','Jonás','Juan','Donata','Flavia' )
City <- c('Madrid','New York','Madrid','Liverpool','Madrid','Buenos Aires','Rome','Liverpool')
City.Id <- c(1,2,1,3,1,4,5,3)
df = data.frame( Name,City,City.Id )

a <- ggplot( df,aes( x = City, text=paste("City.Id=",City.Id)) ) +
geom_bar()

ggplotly(a)

然后我想可视化按高度(=计数)排序的结果条。请注意,我必须保留“City.Id”信息以显示在最终图中。如何才能做到这一点?

最佳答案

鉴于您已经在使用 ggplot2 ,我建议看看还有什么 tidyverse可以提供。即forcats用于处理因子的包。
forcats有一个不错的功能 fct_infreq()这将(重新)设置一个因素的水平,使其按频率顺序排列。如果数据是一个字符向量,还不是一个因子(比如 City 在你的数据中),那么它会首先使它成为一个因子,然后将级别设置为频率顺序。

试试这个代码:

# Load packages
library(ggplot2)
library(forcats)

# Create data
Name <- c( 'Juan','Michael','Andrea','Charles','Jonás','Juan','Donata','Flavia' )
City <- c('Madrid','New York','Madrid','Liverpool','Madrid','Buenos Aires','Rome','Liverpool')
City.Id <- c(1,2,1,3,1,4,5,3)
df = data.frame( Name,City,City.Id )

# Create plot
a <- ggplot(df, aes(x = fct_infreq(City), text=paste("City.Id=",City.Id)) ) +
geom_bar()

a

关于r - 使用 ggplot2 对条形图中的条进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240820/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com