R 如何正确排序轴上的标签?

R 如何正确排序轴上的标签?,r,ggplot2,R,Ggplot2,我正在尝试使用ggplot2创建瀑布图。我的数据: > 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.1

我正在尝试使用
ggplot2
创建瀑布图。我的数据:

> 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
我的代码是:

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
生成的图表:

如您所见,x轴上的名称被弄乱了。我认为这是因为
levels()
函数,因为当我查看它时,它返回按字母顺序排序的值:

> levels(PctCtr$Index)
 [1] "AAPL"  "AIG"   "AMZN"  "C"     "COST"  "ICE"   "KO"    "MMM"   "Total"
[10] "VTR"   "WMT"  

请帮我修一下。谢谢。

您只需在绘图之前对索引列的级别进行因子化和更改即可

PctCtr$Index <- factor(PctCtr$Index, levels=unique(PctCtr[,"Index"]))

PctCtr$Index请帮助我理解为什么这个问题被多次否决。因为这个问题没有清楚地解释什么应该是索引,人们只能猜测它是索引列中列出的一个。如果完全运行,脚本也无法工作。你测试过它吗?你说的“不解释应该是什么”是什么意思?你有没有说明你想要绘制的索引是什么?你只是说它不应该按字母顺序排列。