堆积条形图 ggplot2 - 重新排序填充

Stacked bar charts ggplot2 - reorder fill

我正在使用 ggplot2 绘制堆积条形图。我用变量 car_makecolorproportion 创建了一个数据框 (df_car),后者是数字。有 20 种 car_make 沿着 x 轴,4 种 color 作为填充。每个 car_make 的比例加起来是 1.

我不想按字母顺序排列 car_make,所以我重新排序了:

df_car$car_make <- factor(df_car$car_make, levels = c("toyota", "ford", "mercedes", etc.)

然后我重新排序了填充级别:

df_car$color <- factor(df_car$color, levels = c("red", "white", "black", "silver")

我绘制堆积条形图:

bp_car<- ggplot(df_car, aes(x=car_make, y=proportion, fill=color)) + geom_bar(stat="identity")

x 轴按照我指定的方式出现。但是条形填充的顺序仍然按字母顺序排列......只有图例的顺序响应并按指定显示。表演...

levels(df_car$color)

给...

"red", "white", "black", "silver"

我怎样才能让柱形填充重新排序?

您不需要其中包含颜色名称的数据列(ggplot 在这方面不同于基础图形)。一旦你的汽车水平被适当地排序(就像你所做的那样),你需要设置一个填充颜色比例

bp_car <- ggplot(df_car, aes(x = car_make, y = proportion, fill = car_make)) +
    geom_bar(stat="identity") +
    scale_fill_manual(values = c("red", "white", "black", "silver"))