ggplot重新排序w / interaction

时间:2016-01-13 16:54:11

标签: r interaction geom-bar

我有下表。我需要按Freq订购数据,但是,我还需要显示两个x轴标签 - 一个用于start.station,一个用于end.station,因此我很清楚我在说话关于站对。我使用interaction,但现在不确定如何输入代码以按Freq排序。另外,我想在顶部X轴上显示start.station,在底部X轴上显示end.station。

> new_pairs
 x    y Freq start.latittude start.longitude              start.station
1  359  519  929        40.75188       -73.97770         Pershing\nSquare N
2  477  465 5032        40.75514       -73.98658        Broadway &\nW 41 St
3  484  519 1246        40.75188       -73.97770         Pershing\nSquare N
4  484  318 2654        40.75320       -73.97799 E 43 St &\nVanderbilt\nAve
5  492  267 1828        40.75098       -73.98765        Broadway &\nW 36 St
6  492  498  957        40.74855       -73.98808        Broadway &\nW 32 St
7  492  362 1405        40.75173       -73.98754        Broadway &\nW 37 St
8  493  477 1582        40.75641       -73.99003           W 41 St &\n8 Ave
9  493  529  728        40.75757       -73.99099           W 42 St &\n8 Ave
10 529 2021 1748        40.75929       -73.98860           W 45 St &\n8 Ave
   end.latitude end.longitude        end.station
1      40.75510     -73.97499 E 47 St &\nPark Av
2      40.75641     -73.99003   W 41 St &\n8 Ave
3      40.75500     -73.98014   W 44 St &\n5 Ave
4      40.75500     -73.98014   W 44 St &\n5 Ave
5      40.75020     -73.99093   W 33 St &\n7 Ave
6      40.75020     -73.99093   W 33 St &\n7 Ave
7      40.75020     -73.99093   W 33 St &\n7 Ave
8      40.75680     -73.98291   W 45 St &\n6 Ave
9      40.75680     -73.98291   W 45 St &\n6 Ave
10     40.75757     -73.99099   W 42 St &\n8 Ave    


ggplot(data= new_pairs, aes(x= interaction(end.station,start.station)    y=Freq)) +
  geom_bar(stat="identity") +
  ylab("Bikes received") + 
  xlab("Station") 

enter image description here

1 个答案:

答案 0 :(得分:1)

使用虹膜数据集。我创建了一个交互并使用\ n来拥有两组标签。您只需要为数据集调整scale_x_discrete()表达式,它应该可以工作。

iris$Species2 <- iris$Species
iris$Int <- interaction(iris$Species2, iris$Species)

ggplot(data= iris, aes(x= Int, y=Petal.Length)) + geom_bar(stat="identity") + scale_x_discrete("Int", labels = c("setosa.setosa" = "setosa\nsetosa","versicolor.versicolor" = "versicolor\nversicolor",
  "virginica.virginica" = "virginica\nvirginica"))

enter image description here