0

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

The resulting chart: enter image description here

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.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
AK88
  • 2,946
  • 2
  • 12
  • 31
  • Please help me understand why this question is downvoted multiple times. – Konrad Rudolph Jun 05 '17 at 09:46
  • Because the question does not explain clearly what should be the index, one has to guess it is the one listed in the Index column also the script does not work if run in full. Have you tested it? – Al14 Jun 05 '17 at 09:52
  • what do you mean by does not explain what should be? – AK88 Jun 05 '17 at 09:54
  • Do you state anywhere what's the Index you want to plot? You just say it should no be alphabetical. – Al14 Jun 05 '17 at 09:57

1 Answers1

0

You can just factor and change the levels of the Index column before the plot

PctCtr$Index <- factor(PctCtr$Index, levels=unique(PctCtr[,"Index"]))
Al14
  • 1,734
  • 6
  • 32
  • 55