如何在matplotlib气泡图上显示图例标签

时间:2018-12-31 05:38:06

标签: python matplotlib bubble-chart

我正在尝试在matplotlib气泡图上创建图例标签,但是我没有得到正确的标签

为绘制图例,我尝试创建一个循环以迭代City类型及其对应的气泡颜色,但未获得预期的结果。

图例标签的预期结果应为: 城市类型 带有淡蓝色的城市泡泡图 带有lightskyblue郊区的气泡图 金色金色泡泡图

实际结果: 城市类型 带有浅珊瑚色的气泡图平均票价($)

%matplotlib inline 
# Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


# Create a legend
plt.title("Pyber Ride Sharing Data(2016)")
plt.xlabel("Total Number of Rides(Per City)")
plt.ylabel("Average Fare ($)")
plt.grid(True)

unique_bubble_colors = list(xandy_groupby_df[2].unique()) #['LightCoral', 'LightSkyBlue', 'Gold']
 unique_city_types = list(xandy_groupby_df[1].unique())    #['Urban', 'Suburban', 'Rural']

legd = plt.legend(numpoints=1, loc=1, borderpad=0, frameon=True, framealpha=0.9, title="City Types")

 #----------------------------------------------------------------------------
#loop to the unique city types and its corresponding bubble color to print the legend labels - this the part of the code that I am not getting the expected results

i=0
for handle in legd.legendHandles:
    handle.set_sizes([25.0])
    handle.set_color(unique_bubble_colors[i])
    handle.set_label(unique_city_types[i])
    i =+ 1

 #----------------------------------------------------------------------------- 

plt.show()

0 个答案:

没有答案