おそらく皆さんがご存知のように、美しいグラフを作成するggplot2に頭を悩ませようとしています:)
販売された住宅のトランザクションを含むデータセットがあります (提供: http://support.spatialkey.com/spatialkey-sample-csv-data/ )
x 軸に都市をプロットする折れ線グラフと、4 つの住宅タイプのそれぞれについて、都市ごとのデータファイル内のトランザクション数を示す 4 本の線が必要です。難しそうに思えないので、これを行う方法を 2 つ見つけました。
- カウントを行う中間テーブルとgeom_line ( )を使用して結果をプロットする
- 生データフレームでgeom_freqpoly()を使用する
基本的なチャートは同じように見えますが、チャート番号が異なります。2 は、カウントの値がすべて 0 のプロットが欠落しているようです (たとえば、SACRAMENTO の右側の都市では、Condo、Multi-Family、または Unknown (このグラフでは完全に欠落しているように見えます) のデータはありません)。
個人的には1番よりも2番のメソッドの方が好きです(個人的なことかもしれませんが)。
だから私の質問は次のとおりです:私は何か間違ったことをしていますか、または方法2で0カウントもプロットする方法はありますか?
# line chart example
# setup the libraries
library(RCurl) # so we can download a dataset
library(ggplot2) # so we can make nice plots
library(gridExtra) # so we can put plots on a grid
# get the data in from the web straight into a dataframe (all data is from: http://support.spatialkey.com/spatialkey-sample-csv-data/)
data <- read.csv(text=getURL('http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'))
# create a data frame that counts the number of trx per city/type combination
df_city_type<-data.frame(table(data$city,data$type))
# correct the column names in the dataframe
names(df_city_type)<-c('city','type','qty')
# alternative 1: create a ggplot with a geom_line on the calculated values - to show the nr. trx per city (on the x axis) with a differenct colored line for each type
cline1<-ggplot(df_city_type,aes(x=city,y=qty,group=type,color=type)) + geom_line() + theme(axis.text.x=element_text(angle=90,hjust=0))
# alternative 2: create a ggplot with a geom_freqpoly on the source data - - to show the nr. trx per city (on the x axis) with a differenct colored line for each type
c_line <- ggplot(na.omit(data),aes(city,group=type,color=type))
cline2<- c_line + geom_freqpoly() + theme(axis.text.x=element_text(angle=90,hjust=0))
# plot the two graphs in rows to compare, see that right of SACRAMENTO we miss two lines in plot 2, while they are in plot 1 (and we want them)
myplot<-grid.arrange(cline1,cline2)