当facetting时,ggplot按属性排序和分组

时间:2018-02-23 03:21:12

标签: r ggplot2

使用如下数据框。

text <- "
MAKE,MODEL,ENGINE_VENDOR,ENGINE_MODEL,PRICE,BAND,AGE_MONTHS,CAR_NAME,CAR_COUNT,TOWN_CNT,RIDE_SHARE,MILES
MARUTI,CIAZ,FIAT,FIAT FT9889,,PREMIUM,23,MARUTI CIAZ,2171,11124,0.12,44957
HYUNDAI,XCENT,HYUNDAI,HYUNDAI HY7850,,MID,23,HYUNDAI XCENT,10129,32559,0.58,207986
TESLA,MODEL35,FIAT,FIAT FT3596,,PREMIUM,29,TESLA MODEL35,8448,26550,0.48,123133
HANGSUNG,UNO,FIAT,FIAT 3789,,MID,15,HANGSUNG UNO,9943,31428,0.57,172839
KIA,1601,PINGPONG,PINGPONG PP5067,,HIGH,15,KIA 1601,15598,42076,0.89,321824
HANGSUNG,XT1902_2,PINGPONG,PINGPONG PP6767,,HIGH,5,HANGSUNG XT1902_2,2805,13206,0.16,50289
MARUTI,WAGONR,FIAT,FIAT FT5389,,HIGH,5,MARUTI WAGONR,7995,30832,0.45,189000
HYUNDAI,G935FD,FIAT,FIAT FT9889,,PREMIUM,23,HYUNDAI G935FD,11724,34499,0.67,264230
FORD,XT1760,PINGPONG,PINGPONG PP3767,,MID,7,FORD XT1760,2282,10827,0.13,41856
"
df <- read.table(textConnection(text), sep=",", header = T)

我试图通过同时显示来自同一ENGINE_VENDOR的属性来绘制(条形图)每辆车的4个属性。为此,我订购ENGINE_VENDOR并绘制如下图。

df$ENGINE_VENDOR <- factor(df$ENGINE_VENDOR,
                           levels=c('FIAT','PINGPONG', 'HYUNDAI'))

# from wide to long format
df <- df %>% gather(key=var, val,
                    -c("MAKE","MODEL","ENGINE_VENDOR",
                       "ENGINE_MODEL","PRICE","BAND",
                       "AGE_MONTHS","CAR_NAME"))
# get a fixed order of attributes while faceting
df$key <- factor(df$var, levels = df$var)

# plot
ggplot(df, aes(x=CAR_NAME, y=val, fill = ENGINE_VENDOR)) +
  geom_col(position = 'dodge') +
  facet_wrap(~ key, scales = 'free_y') +
  theme(axis.text.x=element_text(angle=60))

这给出了如下图。我需要对此进行以下更改。

  1. 在每个子图中,对应于同一ENGINE_VENDOR的条形应按'FIAT','PINGPONG', 'HYUNDAI'的顺序组合在一起,每个{{1}的第一个属性值最大的汽车}
  2. x轴刻度标记从条形图的中心偏离一点,需要将标签与刻度线处的条形对齐。
  3. enter image description here

0 个答案:

没有答案