【问题标题】:Sort country names in ggplot2 bar plot [duplicate]在ggplot2条形图中对国家名称进行排序[重复]
【发布时间】:2015-11-16 14:21:42
【问题描述】:

我想绘制按字母顺序排列的国家名称,其中阿根廷位于顶部。当我将 arrange(Country) 更改为 arrange(desc(Country)) 时,数据框按降序排序,但 ggplot 绘制相同。

# Turbines and manufacturers
library(XML)
library(dplyr)
library(ggplot2)

data_url <- "http://www.thewindpower.net/turbines_manufacturers_en.php"

doc <- htmlParse(data_url)

data <- readHTMLTable(doc,
                  colClasses = c("character","character","character"),
                  trim = TRUE,
                  which = 6
                  )

plot_data <- data %>%
    filter(Country != "") %>%
    group_by(Country) %>%
    summarise(Freq = n()) %>%
    arrange(Country)


# A bar graph
ggplot(plot_data, aes(Country , Freq,  fill=Country)) + 
    coord_flip() +
    geom_bar(stat="identity", width=.90) + 
    xlab("") + # Set axis labels
    ylab("") + 
    guides(fill=FALSE) +
    ggtitle("Number of Turbine Manufacturers by Country") + 
    theme_minimal()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    默认情况下,ggplot2 按编码顺序绘制因子。你的是按字母顺序编码的(见levels(plot_data$Country)),但coord_flip()把它搞砸了。你可以使用scale_x_reverse(),但你有一个离散值,所以它不起作用。

    您需要重新调整Country 的因子,使其与当前相反。

    为此,请添加以下行:

    plot_data$Country <- factor(plot_data$Country, levels = rev(levels(plot_data$Country)))
    

    在您的绘图数据之后,但在图表之前。

    【讨论】:

    • 谢谢,我用mutate(Country = factor(Country, levels = rev(levels(Country))))代替,因为我想用dplyr
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多