2021年3月6日星期六

Matplotlib pie charts as scatter plot

I have an interesting problem where I am trying to use multiple matplotlib pie charts as a scatter plot. I have read this post regarding this matplotlib tutorial and was able to get those working. However, I found that I was able to achieve the same results using the built-in pie function and plotting many pie charts on the same axis.

When using this alternative method, I found that after plotting the pie charts the axes lose their labels and whenever you pan the original data is still contained inside of the where the bounds of the original data should be, but the pie charts are only contained inside of the figure canvas.

The following code replicates the issue that I'm having.

import matplotlib.pyplot as plt  import pandas as pd  import random    def rand(): #simulate some random data      return [random.randint(0,100) for _ in range(10)]    def plot_pie(x, ax):       ax.pie(x[['a','b','c']], center=(x['lat'],x['lon']), radius=1,colors=['r', 'b', 'g'])    #my data is stored in a similar styled dataframe that I read from a csv and the data is static  sim_data = pd.DataFrame({'a':rand(),'b':rand(),'c':rand(), 'lat':rand(),'lon':rand()})    fig, ax = plt.subplots()  plt.scatter(x=sim_data['lat'], y=sim_data['lon'], s=1000, facecolor='none',edgecolors='r')  y_init = ax.get_ylim()  x_init = ax.get_xlim()    sim_data.apply(lambda x : plot_pie(x,ax), axis=1)  ax.set_ylim(y_init)  ax.set_xlim(y_init)  plt.show()  

The reason that I reset the x and y limits of the axis is that I assume the pie function automatically sets the bounds of the axes to the last pie chart and this was my work around.

https://stackoverflow.com/questions/66512564/matplotlib-pie-charts-as-scatter-plot March 07, 2021 at 10:06AM

没有评论:

发表评论