I'm trying to create a waterfall chart using ggplot2
. My data:
> PctCtr
Index Volatility sign id end start
1 WMT 0.04894867 pos 1 0.04894867 0.00000000
2 MMM 0.09225684 pos 2 0.14120551 0.04894867
3 AIG 0.18997607 pos 3 0.33118159 0.14120551
4 AAPL 0.11067473 pos 4 0.44185632 0.33118159
5 KO 0.05972203 pos 5 0.50157835 0.44185632
6 COST 0.06088945 pos 6 0.56246780 0.50157835
7 C 0.16428627 pos 7 0.72675407 0.56246780
8 AMZN 0.12803944 pos 8 0.85479351 0.72675407
9 ICE 0.09104894 pos 9 0.94584245 0.85479351
10 VTR 0.05415755 pos 10 1.00000000 0.94584245
11 Total 1.00000000 pos 11 0.00000000 1.00000000
And my code:
GF = ggplot(PctCtr, aes(Volatility, fill = sign)) +
geom_rect(aes(Index,
xmin = id - 0.475,
xmax = id + 0.475,
ymin = end,
ymax = start)) +
scale_y_continuous(labels = percent)
scale_x_discrete("", breaks = levels(PctCtr$Index), labels = levels(PctCtr$Index))
GF
As you can see, the names on x-axis are messed up. I think it is because of levels()
function as when I look at it, it returns alphabetically sorted values:
> levels(PctCtr$Index)
[1] "AAPL" "AIG" "AMZN" "C" "COST" "ICE" "KO" "MMM" "Total"
[10] "VTR" "WMT"
Please help me fix this. Thanks.