简体   繁体   中英

ggplot - ordering x-axis labels by multiple columns

with a table like below

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

When I plot the sales by model using ggplot as below I get the plot in the picture

ggplot(df, aes(x=model, y=sales)) +
  geom_point()

在此处输入图片说明

As expected the x-axis labels for model are in the ascending order as per their levels - Accord comes first and Yeti the last.

> 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 ...
>

However, I need the plot with a different order of model - which is obtained when the table is ordered by tier, make and sales(descending). I can get this ordering for the table as in the code below - how do I get the same order of x-axis labels for model in the plot ?

> 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
> 

You can change the order of factor levels of the model variable then plot. Like this:

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()

The first line changes the order of rows. The second line is the actual reordering. unique(df$model) is the current order of the variable and by using it as the levels of the factor you can plot the data in this order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM