Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot-按多列排序x轴标签_R_Ggplot2 - Fatal编程技术网

R ggplot-按多列排序x轴标签

R ggplot-按多列排序x轴标签,r,ggplot2,R,Ggplot2,有一张像下面这样的桌子 df <- read.table(textConnection(" tier make model sales entry Toyota Yeti 10000 entry Honda Jazz 8000 entry Nissan Sunny 5000 entry Honda Amaze 4000 entry Toyota Model10 3500 entry Nissan Beat 2000 Mid Honda Civic 4000 Mid Toyota Corol

有一张像下面这样的桌子

df <- read.table(textConnection("
tier make model sales
entry Toyota Yeti 10000
entry Honda Jazz 8000
entry Nissan Sunny 5000
entry Honda Amaze 4000
entry Toyota Model10 3500
entry Nissan Beat 2000
Mid Honda Civic 4000
Mid Toyota Corolla 3000
Mid Honda Accord 2500
Mid Nissan Xtrail 2200
Mid Toyota Camry 1800
Mid Nissan Moon 800
"), header = TRUE)

> df
    tier   make   model sales
1  entry Toyota    Yeti 10000
2  entry  Honda    Jazz  8000
3  entry Nissan   Sunny  5000
4  entry  Honda   Amaze  4000
5  entry Toyota Model10  3500
6  entry Nissan    Beat  2000
7    Mid  Honda   Civic  4000
8    Mid Toyota Corolla  3000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
11   Mid Toyota   Camry  1800
12   Mid Nissan    Moon   800

正如所料,
model
的x轴标签按照其级别按升序排列-
Accord
排在第一位,
Yeti
排在最后

> str(df)
'data.frame':   12 obs. of  4 variables:
 $ tier : Factor w/ 2 levels "entry","Mid": 1 1 1 1 1 1 2 2 2 2 ...
 $ make : Factor w/ 3 levels "Honda","Nissan",..: 3 1 2 1 3 2 1 3 1 2 ...
 $ model: Factor w/ 12 levels "Accord","Amaze",..: 12 7 10 2 8 3 5 6 1 11 ...
 $ sales: int  10000 8000 5000 4000 3500 2000 4000 3000 2500 2200 ...
>
但是,我需要具有不同顺序的
model
-图,这是在表按层、品牌和销售(降序)排序时获得的。我可以获得如下代码所示的表格顺序-如何在绘图中获得与
模型
相同的x轴标签顺序

> df[with(df, order(tier, make, -sales)),]
    tier   make   model sales
2  entry  Honda    Jazz  8000
4  entry  Honda   Amaze  4000
3  entry Nissan   Sunny  5000
6  entry Nissan    Beat  2000
1  entry Toyota    Yeti 10000
5  entry Toyota Model10  3500
7    Mid  Honda   Civic  4000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
12   Mid Nissan    Moon   800
8    Mid Toyota Corolla  3000
11   Mid Toyota   Camry  1800
> 

可以更改模型变量的因子级别顺序,然后进行打印。像这样:

df <- df[with(df, order(tier, make, -sales)),]
df$model <- factor(df$model, levels = unique(df$model))
ggplot(df, aes(x=model, y=sales)) +
  geom_point()

df您可以更改模型变量的因子级别顺序,然后进行绘图。像这样:

df <- df[with(df, order(tier, make, -sales)),]
df$model <- factor(df$model, levels = unique(df$model))
ggplot(df, aes(x=model, y=sales)) +
  geom_point()
df