保持ggplot图表中用作X的定性变量的原始顺序 [英] Keeping the original order of a qualitative variable used as X in a ggplot chart

查看:54
本文介绍了保持ggplot图表中用作X的定性变量的原始顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我代表一个折线图,其中X轴由定性变量形成,该定性变量最初不是按字母顺序排序的.

绘制ggplot图表时,它会自动按字母顺序排列X轴.

如何停止ggplot并保持原始顺序?

解决方案

R数据框中具有定性数据的每个列均具有级别"属性.这是该列中唯一值的列表,也是ggplot用于确定事物在图中的显示顺序的方式.默认情况下,ggplot将按字母顺序对事物进行排序.

为了覆盖默认行为,您需要覆盖对某些自定义顺序感兴趣的列的"levels"属性.以下是一些有关如何实现此目标的示例代码:

  df $ MAKE = factor(df $ MAKE,level = c("Honda","Chevy","Toyota")) 

factor()方法会将列转换为因子(以防万一),您也可以在其中设置levels属性.

在运行 ggplot()方法之前,运行与上面类似的代码行,您应该发现ggplot输出将按照您指定的方式对此列中的值进行排序.

I am representing a line chart where the X axis is formed by a qualitative variable, which originally is not alphabetically sorted.

When doing the ggplot chart, it automatically orders the X axis alphabetically.

How can I stop ggplot from doing this and keeping the original order?

解决方案

Each column with qualitative data in an R dataframe has a "levels" attribute. This is a list of unique values in the column and it is what ggplot uses to determine the order of how things appear in your plots. By default, ggplot will order things alphabetically.

In order to override the default behavior, you need to override the "levels" attribute for the column you're interested in applying some custom order to. Here is some example code on how you may achieve that:

df$MAKE = factor(df$MAKE, levels = c("Honda", "Chevy", "Toyota"))

The factor() method will convert the column to a factor (in case it isn't already) and you can set the levels attribute in there as well.

Run a line of code similar to the above prior to running the ggplot() method and you should find that your ggplot output will order the values in this column in the way you dictated.

这篇关于保持ggplot图表中用作X的定性变量的原始顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆