In [ ]:
gem 'nyaplot', '0.1.5'
require 'nyaplot'
require 'mapnya'

Case 1: The bubble chart

Mapnya bundles countries as its default map and dataset.It prepares Nyaplot::Countries as the usefult wraper for countries. Nyaplot::Countries.df shows its default dataframe. The dataframe countains information of each country, like name, cca3, location(lat and lng), region, and area.

In [ ]:
raw_df = Nyaplot::Countries.df

Pick up some columns from the dataframe.

In [ ]:
hash = [:name, :lat, :lng, :area].map{|label| {label => raw_df.column(label).to_a}}.reduce({}){|memo, hash| memo.merge(hash)}
df = Nyaplot::DataFrame.new(hash)

Then, let's make a bubble chart to visualize the area of each country. First, choose colorset in which each bubble will be filled.

In [ ]:
color = Nyaplot::Colors.Reds

Then instantiate Nyaplot::MapPlot and add scatter. The result is shown below.

In [ ]:
plot = Nyaplot::MapPlot.new
sc = plot.add_with_df(df, :scatter, :lng, :lat) # x->:lng, y->lat
sc.configure do
  tooltip_contents([:capital, :name, :area])
  color(color)
  size([10, 100000])
  size_by(:area)
  fill_by(:area)
end
plot.show

Case2 :Fill countries in different colors

Footnote: Figures are for estimated total military expenditure. China has published its own military expenditure data. See: www.stats.gov.cn.

In [ ]:
path = File.expand_path("../data/UNdata_Export_20140813_215958400.csv", __FILE__)
df = Nyaplot::DataFrame.from_csv(path)
df.filter! {|row| !row[:value].nil?}
df
In [ ]:
hash = [:name, :lat, :lng, :cca3].map{|label| {label => raw_df.column(label).to_a}}.reduce({}){|memo, hash| memo.merge(hash)}
new_df = Nyaplot::DataFrame.new(hash)
countries = new_df.column(:name).to_a
df.filter!{|row| !countries.index(row[:country_or_area]).nil?}
df.filter!{|row| row[:year]==2012}
df
In [ ]:
countries = df.column(:country_or_area).to_a; value = []
new_df.each_row do |row|
  if countries.index(row[:name]).nil?
    value.push(-1)
  elsif
    name = row[:name]
    value.push(df.filter{|row| row[:country_or_area] == name}.column(:value).to_a[0])
  end
end
new_df.value = value
new_df
In [ ]:
color = Nyaplot::Colors.Blues
In [ ]:
sc_df = new_df.filter{|row| row[:value]>0}

plot = Nyaplot::MapPlot.new
plot.fill_map_with_df(new_df, :cca3, :value)
sc = plot.add_with_df(sc_df, :scatter, :lng, :lat)
sc.tooltip_contents([:name, :cca3, :value])
sc.color("#fff")
  plot.color(color)
plot.show