How to divide a panda image into hexagons?ΒΆ
pandas is an extremely powerful library to analyze, combine and manipulate data in many ways. It provides a class for tables called DataFrames that are inspired from R. DataFrames have an index column and functions for plotting and reading from CSV or Excel files are included by default. Pandas uses numpy under the hood.
Install it with:
pip install pandas
The library can do a lot more than can be described here. See the pandas go to space tutorial for a deeper overview.
The following code creates some eye candy:
# create a hex-binned plot from randomly sampled panda pixels
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from PIL import Image
# read image and convert it to a numpy array
panda = np.array(Image.open('panda.png'))
panda = panda[:,:,:3].mean(axis=2) # aggregate each color channel separately
print(panda.shape) # rows and columns
pixels = pd.DataFrame(255 - panda)
# extract dark pixels
pixels = pixels.unstack()
pixels = pixels[pixels > 0]
# select 10% of pixels
n_points = pixels.shape[0] // 10
sample = pixels.sample(n_points)
# create new table from indices
coords = sample.index.to_frame().values
df = pd.DataFrame({'x': coords[:,0], 'y': -coords[:,1], 'n': sample.values})
df.plot.hexbin(x='x', y='y', gridsize=24, cmap="Greys")
plt.savefig('hexpanda.png')