本文整理汇总了Python中matplotlib.pyplot.pie方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.pie方法的具体用法?Python pyplot.pie怎么用?Python pyplot.pie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.pie方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: analyseSex
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def analyseSex(firends):
sexs = list(map(lambda x:x['Sex'],friends[1:]))
counts = Counter(sexs).items()
counts = sorted(counts, key=lambda x:x[0], reverse=False)
counts = list(map(lambda x:x[1],counts))
labels = ['Unknow','Male','Female']
colors = ['red','yellowgreen','lightskyblue']
plt.figure(figsize=(8,5), dpi=80)
plt.axes(aspect=1)
plt.pie(counts,
labels=labels,
colors=colors,
labeldistance = 1.1,
autopct = '%3.1f%%',
shadow = False,
startangle = 90,
pctdistance = 0.6
)
plt.legend(loc='upper right',)
plt.title(u'%s的微信好友性别组成' % friends[0]['NickName'])
plt.show()
示例2: analysis_mobile
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def analysis_mobile(self):
# self.record_result('<strong style="color: black; font-size: 24px;">正在分析该商品不同省份的购买量...</strong>')
fig_size = plt.rcParams["figure.figsize"]
plt.figure(figsize = (2.4, 2.4))
obj = self.data_frame['is_mobile']
obj = obj.value_counts()
obj = obj.rename({1: '移动端', 0: 'PC'})
plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.7, labels = obj.index, startangle = 180)
plt.title('该商品移动/ PC 购买比例')
plt.tight_layout()
filename = '%s_mobile.png' % self.product_id
plt.savefig('%s/%s' % (utils.get_save_image_path(), filename))
plt.figure(figsize = fig_size)
plt.clf()
result = utils.get_image_src(filename = filename)
self.record_result(result, type = 'image')
# 分析购买后评论的时间分布
示例3: visualize_distributions
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def visualize_distributions(distro_dict, threshold=10):
import matplotlib.pyplot as plt
key_list = sorted(distro_dict.keys())
threshold_str = '%d+' % (threshold, )
label_list = [
threshold_str if key == threshold else str(key)
for key in key_list
]
size_list = [ distro_dict[key] for key in key_list ]
color_list = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = [0.0] + [0.0] * (len(size_list) - 1)
plt.pie(size_list, explode=explode, labels=label_list, colors=color_list,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
plt.show()
示例4: test_pie_center_radius
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def test_pie_center_radius():
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
wedgeprops={'linewidth': 0}, center=(1, 2), radius=1.5)
plt.annotate("Center point", xy=(1, 2), xytext=(1, 1.5),
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3"))
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
示例5: test_pie_textprops
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def test_pie_textprops():
data = [23, 34, 45]
labels = ["Long name 1", "Long name 2", "Long name 3"]
textprops = dict(horizontalalignment="center",
verticalalignment="top",
rotation=90,
rotation_mode="anchor",
size=12, color="red")
_, texts, autopct = plt.gca().pie(data, labels=labels, autopct='%.2f',
textprops=textprops)
for labels in [texts, autopct]:
for tx in labels:
assert tx.get_ha() == textprops["horizontalalignment"]
assert tx.get_va() == textprops["verticalalignment"]
assert tx.get_rotation() == textprops["rotation"]
assert tx.get_rotation_mode() == textprops["rotation_mode"]
assert tx.get_size() == textprops["size"]
assert tx.get_color() == textprops["color"]
示例6: label_distribution
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def label_distribution(trainFile):
labels=[]
with open(trainFile,'r') as f:
raw_data=f.readlines()
for line in raw_data:
line=line.strip().split("+++$+++")
label=int(line[2])
assert label in [0,1],"Invalid label value!"
labels.append(label)
neg_count=labels.count(0)
pos_count=len(labels)-neg_count
counts=[neg_count,pos_count]
labels=["negative","positive"]
fig=plt.figure(figsize=(9,9))
# 画饼图(数据,数据对应的标签,百分数保留两位小数点)
plt.pie(counts, labels=labels, autopct='%1.2f%%')
plt.title('Train Label Distribution', bbox={'facecolor': '0.8', 'pad': 5})
plt.show()
savePath=trainFile.split(".")[0]+"_ld.png"
fig.savefig(savePath)
plt.close()
示例7: pieGraphics
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def pieGraphics(Labels,ValueList,graphicTitle='图例'):
# The slices will be ordered and plotted counter-clockwise.
#labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
#sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(ValueList, 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.show()
#barGraphics('等级','数量',['A','B','C','D','E','F'],[29,30,40,47,38,23],'测试图例')
#linePlotGraphics("xLabel","yLabel",[1,2,3,4,5,6,7,8,9,10],[1.1,1.9,2.6,3.6,9.8,14,24,40,80,150],graphicTitle='图例')
#scatterPlotsGraphics("xLabel","yLabel",[1,2,3,4,5,6,7,8,9,10],[1,11.9,2,6.3,6,9.8,14,4,8,5],graphicTitle='图例')
示例8: pieGraphics
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def pieGraphics(Labels,ValueList,graphicTitle='图例'):
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"]
maxdata = max(ValueList)
explode = []
for v in ValueList:
if v == maxdata:
explode.append(0.1)
else:
explode.append(0)
print(explode)
patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90)
for font in l_text:
font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF'))
plt.title(graphicTitle,fontproperties=font_set,y=1.05)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()
示例9: plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def plot(sizes,plotname):
fig = plt.figure(figsize=(2.0,2.0),facecolor='white')
ax = plt.subplot(111)
psizes = ['%1.1f%%' % (x/sum(sizes)*100) for x in sizes]
labels = [x+'\n'+y for x,y in zip(LABELS,psizes)]
patches = plt.pie(sizes, colors=COLORS, labels=labels,
shadow=False, startangle=90, labeldistance=0.7,
wedgeprops={'linewidth': 4})
for pie_wedge in patches[0]:
pie_wedge.set_edgecolor('white')
for t in patches[1]:
t.set_horizontalalignment('center')
plt.axis('equal')
plt.tight_layout()
plt.savefig(plotname)
print('saved plot to {}'.format(plotname))
plt.show()
######################################################
# Data processing
示例10: graph
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def graph():
total = len(os.listdir(test_path))
affected = pandas.read_csv('output.csv')
affected = affected['output'].sum()
healthy = total - affected
piey = ['Glaucomatous', 'Healthy']
piex = [affected, healthy]
plt.axis('equal')
plt.pie(piex, labels=piey, radius=1.5, autopct='%0.1f%%', explode=[0.2, 0])
plt.show()
# Frontend GUI
示例11: test_pie_frame_grid
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def test_pie_frame_grid():
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
# only "explode" the 2nd slice (i.e. 'Hogs')
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
wedgeprops={'linewidth': 0},
frame=True, center=(2, 2))
plt.pie(sizes[::-1], explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
wedgeprops={'linewidth': 0},
frame=True, center=(5, 2))
plt.pie(sizes, explode=explode[::-1], labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
wedgeprops={'linewidth': 0},
frame=True, center=(3, 5))
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
示例12: create_pie_chart
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def create_pie_chart(elements, suptitle, png, figure_id):
"""
Create pie chart
:param elements: dict with elements (dict)
:param suptitle: name of chart (str)
:param png: name of output file (str)
:param figure_id: id of current plot (started with 1) (int)
:return: None
"""
values = [value for value in elements.values()]
keys = [key for key in elements.keys()]
plt.figure(figure_id)
plt.subplots_adjust(bottom=.05, left=.01, right=.99, top=.90, hspace=.35)
explode = [0 for x in range(len(keys))]
max_value = max(values)
explode[list(values).index(max_value)] = 0.1
plt.pie(values, labels=keys,
autopct=make_autopct(values), explode=explode,
textprops={'fontsize': PIE_LABEL_FONT_SIZE})
plt.axis("equal")
plt.suptitle(suptitle, fontsize=PIE_SUPTITLE_FONT_SIZE)
plt.gcf().set_dpi(PIE_DPI)
plt.savefig("{dest}/{png}/{result_file}".format(dest=RESULTS_DIR,
png=PNG_DIR,
result_file=png))
示例13: plot_recursive
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def plot_recursive(self, attrs, base_folder, base_time, div_number):
# Creating a folder named aatr+'_children' which contains the plot of the attr children, a plot showing time division at that level
labels = []
values = []
sum_time = 0
for attr in attrs['children']:
labels.append(attr['name'])
values.append(attr['time'])
sum_time += attr['time']
arg = np.argsort(values)
labels = np.array(labels)[arg].tolist()
values = np.array(values)[arg]
plt.pie(values, labels=labels, autopct='%1.1f%%')#, radius=len(labels)
plt.xlabel(attrs['name']+'\n'+'Unaccounted Time: '+str((base_time - sum_time))+'\nTotal Time: '+str(base_time))#/div_number
if not os.path.exists(base_folder+'/'+str(attrs['name'])):
os.mkdir(base_folder+'/'+str(attrs['name']))
plt.savefig(base_folder+'/'+str(attrs['name'])+'/'+str(attrs['name'])+'.png')
plt.clf()
if len(attrs['children']) != 0:
for i in attrs['children']:
if len(i['children']):
self.plot_recursive(i.copy(), base_folder+'/'+str(attrs['name']), i['time'], div_number)#/div_number
示例14: parse_args
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def parse_args():
parser = argparse.ArgumentParser(description=
"Create a pie chart showing the most active users in a Telegram chat")
required = parser.add_argument_group('required arguments')
required.add_argument('-f','--file',
help='the jsonl chatlog file to analyse',
required = True
)
parser.add_argument(
'-o', '--output-folder',
help='the folder to save the pie chart image in.'
'Using this option will make the graph not display on screen.')
parser.add_argument(
'-s','--figure-size',
help='the size of the figure shown or saved (X and Y size).'
'Choose an appropriate value for your screen size. Default 12 8.',
nargs=2,type=int,default = [12,8]
)
parser.add_argument(
'-m','--minimum-percentage',
help='the minimum percentage of activity a person must contribute '
'to get their own slice of the pie chart. Default 2',
type=float,default=2
)
parser.add_argument(
'-d','--date-range',
help='the range of dates you want to look at data between. '
'Must be in format YYYY-MM-DD YYYY-MM-DD with the first date '
'the start of the range, and the second the end. Example: '
"-d '2017-11-20 2017-05-15'. Make sure you don't put a day "
'that is too high for the month eg 30th February.',
default="1000-01-01 4017-01-01"
#hopefully no chatlogs contain these dates :p
)
return parser.parse_args()
示例15: make_trimmed_ddict
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import pie [as 别名]
def make_trimmed_ddict(counter,total_datapoints,names,min_percent):
trimmedCounter = defaultdict(int)
#find percentile to start adding people to "other" at
min_chars = (min_percent/100) * total_datapoints
for person, frequency in counter.items():
if frequency < min_chars:
trimmedCounter["other"] += frequency
else:
if names[str(person)] == "other":
print("Someone in this chat is called 'other'. "
"They will be absorbed into the 'other' pie slice.")
trimmedCounter[names[str(person)]] = frequency
return trimmedCounter