With a data frame like below.
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)
I'm trying to plot (bar plots) the 4 attributes per car by showing the ones from same ENGINE_VENDOR
together. For this purpose I order the ENGINE_VENDOR
and plot as follows.
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))
This gives a plot like below. I need to get the following changes to this.
- In each sub-plot, the bars corresponding to the same
ENGINE_VENDOR
should come together in the order of'FIAT','PINGPONG', 'HYUNDAI'
, with the car with the largest value for the attribute first for eachENGINE_VENDOR
- The x-axis tick mark labels are off from the center of the bar by a bit, need to get the label aligned with the bar at the tick mark.