本文整理汇总了Python中matplotlib.pyplot.pie函数的典型用法代码示例。如果您正苦于以下问题:Python pie函数的具体用法?Python pie怎么用?Python pie使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pie函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: comparison_pie_plot
def comparison_pie_plot(path, data, txt):
"""
Plots a pie chart comparison of the # of times each AD found
the highest best/average final solution for all simulations
"""
# The slices will be ordered and plotted counter-clockwise.
unzipped_data = list(zip(*data))
num_sims = len(unzipped_data)
sizes = [0] * len(data)
for simulation_data in unzipped_data:
m = max(simulation_data)
max_indexes = [i for i, j in enumerate(simulation_data) if j == m]
for i in max_indexes:
sizes[i] += 1
# percentages
for i in range(len(sizes)):
sizes[i] = round((sizes[i] / num_sims) * 100)
# "explode" all slices
explode = [0.1] * len(data)
plt.figure()
plt.title("Comparison of the # of times each AD found the highest " + txt + " final solution for all simulations")
plt.pie(sizes, explode=tuple(explode), labels=AD_labels, colors=AD_color, autopct='%1.1f%%', shadow=True)
plt.axis('equal') # Set aspect ratio to be equal so that pie is drawn as a circle.
plt.savefig(path + "/pie_" + txt + ".png", bbox_inches='tight')
plt.close()
return
示例2: display_channel_efficiency
def display_channel_efficiency(self):
size = 0
start_time = self.pcap_file[0].time
end_time = self.pcap_file[len(self.pcap_file) - 1].time
duration = (end_time - start_time)/1000
for i in range(len(self.pcap_file) - 1):
size += len(self.pcap_file[i])
ans = (((size * 8) / duration) / BW_STANDARD_WIFI) * 100
ans = float("%.2f" % ans)
labels = ['utilized', 'unutilized']
sizes = [ans, 100.0 - ans]
colors = ['g', 'r']
# Make a pie graph
plt.clf()
plt.figure(num=1, figsize=(8, 6))
plt.axes(aspect=1)
plt.suptitle('Channel efficiency', fontsize=14, fontweight='bold')
plt.title("Bits/s: " + str(float("%.2f" % ((size*8)/duration))),fontsize = 12)
plt.rcParams.update({'font.size': 17})
plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2)
plt.show()
示例3: plot_percent_mentions
def plot_percent_mentions(tweets, gop = False, save_to = None):
'''
Plots the percent mentions of each candidate (filtered for party)
Used for Task 3.
'''
percents = tweets.get_percent_mentions(gop)
candidates = []
mentions = []
for c, ment in percents:
if c == "other":
other_v = ment
else:
candidates.append(CANDIDATE_NAMES[c[:-1]])
mentions.append(ment)
candidates.append("other")
mentions.append(other_v)
fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))
plt.pie(mentions, labels = candidates, autopct='%1.1f%%')
if gop:
plt.title("Percent of Mentions per GOP candidate")
else:
plt.title("Percent of Mentions per candidate")
plt.show()
if save_to:
fig.savefig(save_to)
示例4: plotPieChart
def plotPieChart(self, title=None, cmap_name='Pastel2'):
if sys.hexversion >= 0x02700000:
self.fig.set_tight_layout(True)
# Generate plot data
labels, ydata = self._getPlotData()
totalobjects = float(np.sum(ydata))
fracs = [ynum / totalobjects for ynum in ydata]
explode = np.zeros(len(fracs)) # non zero makes the slices come out of the pie
# plot pie chart
cmap = plt.cm.get_cmap(cmap_name)
colors = cmap(np.linspace(0., 0.9, len(fracs)))
plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=False, startangle=90,
colors=colors)
# generate plot / axis labels
for axis in self.ax.get_xticklabels():
axis.set_fontsize(self.xticksize)
if self.unit is None: # NOTE this is hacked in so it only works with DataPerParameterClass
self.unit = self._getParLabelAndUnit(self._planetProperty)[1] # use the default unit defined in this class
self._yaxis_unit = self.unit
if title is None:
title = 'Planet {0} Bins'.format(self._gen_label(self._planetProperty, self.unit)) # NOTE not always planet
plt.title(title)
plt.xlim(-1.5, 1.5)
示例5: analyzeData
def analyzeData(db):
# Total calls, incoming, outgoing (and percents). Times to/from liz and percentage.
cursor = db.cursor()
numCalls = cursor.execute('''SELECT Count(*) FROM calls''').fetchone()[0]
print numCalls, "calls from May to July 2014."
numIncoming = cursor.execute('''SELECT Count(*) FROM calls WHERE incoming=1''').fetchone()[0]
print numIncoming, "incoming calls. (" + str((numIncoming*100.0)/numCalls) + "%)"
numOutgoing = cursor.execute('''SELECT Count(*) FROM calls WHERE incoming=0''').fetchone()[0]
print numOutgoing, "outgoing calls. (" + str((numOutgoing*100.0)/numCalls) + "%)"
# Display the info in a pie chart
labels = 'Incoming Calls', 'Outgoing Calls'
values = [numIncoming, numOutgoing]
colors = ['orange', 'seagreen']
plt.pie(values, labels=labels, colors=colors, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
numLiz = cursor.execute('''SELECT Count(*) FROM calls WHERE phone_number='630-380-4152';
''').fetchone()[0]
percentLiz = (numLiz*100.0)/numCalls
print numLiz, "calls to/from Liz. (" + str(percentLiz) + "%)"
# Display the info in a pie chart
labels = 'Liz', 'Others'
sizes = [int(percentLiz), 100 - int(percentLiz)]
colors = ['turquoise', 'gold']
plt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
return
示例6: plot_NA_ratio_features
def plot_NA_ratio_features(dataset, feature_names, missing_value_string='nan'):
y, x = dataset.shape
ind = np.zeros((x, 1)).reshape(1, x)
for j in range(y):
for i in range(x):
# print str(dataset[j, i])
if missing_value_string == str(dataset[j, i]):
ind[0, i] += 1
ind = (ind/y*100)
labels = 'NA', ''
colors = ['yellowgreen', 'lightcoral']
explode = (0, 0)
plt.rcParams.update({'font.size': 8})
plt.suptitle("NA ration", fontsize=16)
for i in range(x):
ax = plt.subplot(5, 5, i+1)
ax.set_title(feature_names[i])
sizes = [ind[0, i], 100-ind[0, i]]
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%')
# autopct permits to add the value of the part in chart
plt.axis('equal')
plt.show()
示例7: create_pie_chart
def create_pie_chart(data, title, filename, cutoff=0.01, verbose=False):
"""Create a pie chart from the given data
Params:
data- a collections.Counter where the keys should be the labels to
the graph
"""
total = float(sum(data.values()))
frac_labels = []
other_count = 0
# compute the fraction for each label
for cnt in data.keys():
fraction = float(data[cnt]) / total
if verbose:
print "{}: {}".format(cnt, fraction)
# if this slice is too small, just add it to other small
# totals and display them together
if fraction < cutoff:
other_count += data[cnt]
continue
frac_labels.append((fraction, cnt))
if other_count > 0:
frac_labels.append((float(other_count) / total, "Other"))
frac_labels.sort(key=lambda entry: entry[1])
fractions, labels = zip(*frac_labels)
plt.figure()
plt.pie(fractions, labels=labels, autopct='%1.1f%%',
colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'))
plt.title(title)
plt.savefig(filename, fmt='pdf')
示例8: pie_graph
def pie_graph(conn, query, output, title='', lower=0, log=False):
labels = []
sizes = []
res = query_db(conn, query)
# Sort so the graph doesn't look like complete shit.
res = sorted(res, key=lambda tup: tup[1])
for row in res:
if row[1] > lower:
labels.append(row[0])
if log:
sizes.append(math.log(row[1]))
else:
sizes.append(row[1])
# Normalize.
norm = [float(i)/sum(sizes) for i in sizes]
plt.pie(norm,
labels=labels,
shadow=True,
startangle=90,
)
plt.figtext(.1,.03,'{}\n{} UTC'.format(site,generation_time))
plt.axis('equal')
plt.legend()
plt.title(title)
plt.savefig(output)
plt.close()
示例9: pieplot
def pieplot(data, total, min, stitle): #Create a pie plot... mmm, pie
import matplotlib.pyplot as plt
labels=[]
sizes=[]
other=0
if total is None: #Calc total if not given
total=0
for cat in data:
total+=cat[0]
for cat in data: #Convert values to a percentage of total, separate smaller categories
cat[0]=cat[0]/total*100
if cat[0]>min:
labels.append(cat[1])
sizes.append(cat[0])
else:
other+=cat[0]
if other>0.1: #Include the rest if it's significant
sizes.append(other)
labels.append("Other")
# The slices will be ordered and plotted counter-clockwise.
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
#explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice # But I don't wanna explode...
plt.pie(sizes, labels=labels, #colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal') # Set aspect ratio to be equal so that pie is drawn as a circle.
plt.title(stitle)
plt.show()
示例10: plotResults
def plotResults(red_wins, black_wins, tie):
# Adjusting the plot results to not show 0%`s
def make_autopct(values):
def my_autopct(pct):
if pct == 0:
return ""
else:
return '{p:.1f}% '.format(p=pct)
return my_autopct
# Setting up plot variables
labels = ['Red Wins', 'Black Wins', 'Ties']
sizes = [red_wins, black_wins, tie]
colors = ['yellowgreen', 'gold', 'lightskyblue']
explode = (0.1, 0, 0)
plt.pie(sizes, colors=colors, explode=explode, labels=labels, autopct=make_autopct(sizes), shadow=True,
startangle=70)
plt.axis('equal')
plt.tight_layout()
plt.show()
print "number of red wins ", red_wins
print "number of black wins ", black_wins
print "number of ties ", tie
示例11: plot_single_piechart
def plot_single_piechart(self, cluster_no, labels, pdf):
cluster_label_dict = {}
for label in labels:
if label not in cluster_label_dict:
cluster_label_dict[label] = 1
else:
cluster_label_dict[label] += 1
distinct_labels = []
label_counts = []
colors = []
cmap = self.get_cmap(30)
i = 0
for label,value in cluster_label_dict.iteritems():
colors.append(cmap(i))
distinct_labels.append(label)
label_counts.append(value)
i = i+1
matplotlib.rcParams['font.size'] = 5
plt.figure(figsize=(8,8))
plt.pie(label_counts, explode=None, labels=distinct_labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.suptitle("Cluster no " + str(cluster_no) + "\nNumber of docs in cluster: " + str(len(labels)),fontsize=10)
pdf.savefig()
plt.close()
示例12: drawing_pie
def drawing_pie(start_date, end_date):
p_count=0
n_count=0
neu_count=0
sentiment = get_sentiment_dates(start_date,end_date)
for semt in sentiment[0].values():
p_count+=semt
for semt in sentiment[1].values():
n_count+=semt
for semt in sentiment[2].values():
neu_count+=semt
print p_count
print n_count
print neu_count
labels = 'Positive','Negative','Neutral'
sizes = [p_count,n_count,neu_count]
colors = ['green', 'red', 'yellow']
explode = (0, 0.1, 0) # only "explode" the 2nd slice
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
plt.title('Sentiment is Positive')
plt.show()
return
示例13: makePieChart
def makePieChart(bigList):
streetNameList = []
bikeSpaceList = []
x = 0
##bigList = readBikeData.GatherData('rows.json')
for i in range(len(bigList)):
streetName = bigList[i][10].lower()
bikeSpaceInt = int(bigList[i][12])
if streetName in streetNameList:
ndx = streetNameList.index(streetName)
bikeSpaceList[ndx] += bikeSpaceInt
else:
streetNameList.append(streetName)
bikeSpaceList.append(bikeSpaceInt)
bikeSpaceSum = sum(bikeSpaceList)
##I omited any area that was less then 1% of the total bike space to get a cleaner pie chart
while x < len(bikeSpaceList):
if(bikeSpaceList[x] < (bikeSpaceSum * .01) and x >= 0):
del bikeSpaceList[x]
del streetNameList[x]
x-=1
else:
x+=1
plt.axis("equal")
plt.pie(bikeSpaceList, labels = streetNameList, autopct = "%1.1f%%", shadow = False)
plt.title("Bike Space to Street Name Distribution")
plt.show()
示例14: pieplot
def pieplot(self, variable):
""" Plot pie plot for gender or usertype in certain period """
variable_type = self.data[variable].unique()
variable_size = []
if variable == 'gender':
for i in np.sort(variable_type):
variable_size.append(round((sum(self.data[variable] == i) / self.data.shape[0] * 100), 2)) # calculate distirbution
# Gender (Zero=unknown; 1=male; 2=female)
labels = 'Unknown', 'Male', 'Female'
sizes = variable_size
colors = ['lightyellow','lightskyblue', 'lightcoral']
explode = (0, 0.1, 0.1) # "explode" the distribution of male and female
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.title('Gender Distribution in {}-{}'.format(self.year, self.month), fontsize = 12,y = 1,x=0.12,bbox={'facecolor':'0.8', 'pad':5})
plt.show()
elif variable == 'usertype':
# usertype (Zero=Customer, 1=Subscriber)
for i in range(2): # change to 0, 1
variable_size.append(round((sum(self.data[variable] == i) / self.data.shape[0] * 100), 2)) # calculate distribution
labels = 'Subscriber', 'Customer'
sizes = variable_size
colors = ['lightcoral','lightskyblue']
explode = (0, 0.1) # only "explode" the subscriber
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.title('User Type Distribution in {}-{}'.format(self.year, self.month), fontsize = 12,y = 1,x=0.12,bbox={'facecolor':'0.8', 'pad':5})
plt.show()
示例15: make_chart_pie_chart
def make_chart_pie_chart():
plt.pie([0.95, 0.05], labels=["Uses pie charts", "Knows better"])
# make sure pie is a circle and not an oval
plt.axis("equal")
plt.show()