Python Matplotlib标注

时间:2017-04-12 04:04:12

标签: python pandas matplotlib

我之前已经问过以下问题,但是我很难尝试实现我的代码中提供的示例,以便在'callout'或'Annotation'中获取标签,因此文本不会重叠。我希望有人能够帮助我。这是我之前的问题。 Python PieChart (is it possible to do CallOut labels)

到目前为止,这是我的代码:

from collections import Counter
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import sqlite3
import os
#Connect to Database
mypath = os.path.abspath(__file__)
conn =sqlite3.connect('C:\inetpub\wwwroot\db\DeviceRegister.sqlite3')
#Connect to the sqlite3 database
cursor = conn.cursor()  # Set cursor as the cursor for plus.sqlite
#SQL Query
df = pd.read_sql_query("SELECT devices.id AS id, macs.address AS mac,     oses.name AS os, browsers.name AS browser FROM devices JOIN macs ON devices.mac = macs.id JOIN oses ON devices.os = oses.id JOIN browsers ON devices.browser = browsers.id", conn)
df_browsers = df.drop_duplicates(subset=['mac','browser'])
#Get Data
counterbrowsers = Counter(df_browsers['browser'])
browser_names = counterbrowsers.keys()
browser_counts = counterbrowsers.values()
#Pie Chart
plt.figure(figsize=plt.figaspect(0.3))
labels, values = zip(*sorted(counterbrowsers.items(), key=lambda x:   x[1])) #Counteros is the Dictionary-like object we are trying to sort.  
This 'zip' solves the problem of sorting each of them independently.
This   
will sort as pairs, by value.
labels = ['{0} : {1:1}'.format(i,j) for i,j in zip(labels, values)]
colors = ['yellowgreen', 'gold', 'lightskyblue',  'lightcoral','#008DB8','#00AAAA','#001CF0','#00FF80','c','m','r','b','#1970','#0038E2','#0055D4','#0071C6','#00E28E', '#00C69C']
explode = list()
for k in labels:
explode.append(0.1)
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
        val=int(round(pct*total/100))
    return '{p:.0f}%  ({v:d})'.format(p=pct,v=val)
return my_autopct
pie = plt.pie(values, labels=labels, explode=explode, colors=colors, shadow=True, startangle=90, autopct=make_autopct(values))  
plt.suptitle('Browsers Analytics', bbox={'facecolor':'0.8', 'pad':7})
plt.legend(labels, loc="lower right")
plt.axis('equal') # Set aspect ratio to be equal so that pie is drawn as a circle, # View the plot drop above
plt.savefig(mypath + 'piebrowsers.png')

1 个答案:

答案 0 :(得分:0)

使用plt.legend(loc='location you want it to appear')

即。 plt.legend(loc='upper left')

'最好的' :0, '右上角' :1, '左上角' :2, '左下角' :3, '右下角' :4, '右' :5, 左中心' :6, '中右?' :7, '下中心' :8, '上中心' :9, '中心' :10,

了解更多信息。 http://matplotlib.org/1.3.0/api/legend_api.html