Python matplotlib.pyplot.pie() Examples

The following are code examples for showing how to use matplotlib.pyplot.pie(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: wechat-analyse   Author: qinyuanpei   File: main.py    MIT License 6 votes vote down vote up
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() 
Example 2
Project: RiboCode   Author: xryanglab   File: pie_plot.py    MIT License 6 votes vote down vote up
def pie(orderDict, outname):
	sizes = list(orderDict.values())
	total = sum(sizes)
	labels = []
	for i in orderDict.keys():
		perct = orderDict[i] / float(total)
		labels.append("%s: %i (%s)" % (i,int(orderDict[i]),percentage_format(perct,1)))

	colors = get_colors(len(labels))
	plt.figure(figsize=(8,6))
	patches, text = plt.pie(sizes, startangle=90,colors=colors)
	plt.legend(patches,labels,loc=4,bbox_to_anchor=(1, 0),fontsize=15)
	plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
	plt.tight_layout()
	plt.savefig(outname + "_ORFs_category.pdf")
	plt.close() 
Example 3
Project: hub-py   Author: esridc   File: hub.py    Apache License 2.0 6 votes vote down vote up
def _pie_chart(self, df, attribute):
        """
        Generates a pie chart for given attribute if number of categories < 7.
        """
        
        #Data to plot
        types = list(df[attribute].unique())
        types = [category for category in types if category]
        sizes = df[attribute].value_counts()
        #Plot
        plt.figure(figsize=(6,6))
        plt.title('Pie chart for '+attribute)
        plt.pie(sizes, labels=types,
            autopct='%1.2f%%', shadow=True, startangle=100)
        plt.axis('equal')
        #results.append(plt)
        plt.show() 
Example 4
Project: browser-history-analyzer   Author: chitianhao   File: statistic.py    Apache License 2.0 6 votes vote down vote up
def plot(counts_sorted, number=10):
    """ plot the pie chart of the frequent visited website """

    plt.figure(1, figsize=(10, 10))
    plt.title('Top $n Sites Visited'.replace('$n', str(number)))
    # the count is sizes, the url is labels
    labels = []
    sizes = []

    count = 0
    for key, value in counts_sorted.items():
        labels.append(key)
        sizes.append(value)
        count += 1
        if count >= number:
            break

    # make the plot, save it and show it
    plt.pie(sizes, autopct='%1.1f%%', labels=labels)
    plt.savefig("statistics.jpg")
    print("The statistics plot is saved as statistics.jpg")
    plt.show() 
Example 5
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
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') 
Example 6
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
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"] 
Example 7
Project: EvieeBot   Author: EvieePy   File: stats.py    MIT License 6 votes vote down vote up
def make_pie(self):

        labels = 'Online', 'Offline', 'DnD', 'Idle'
        fracs = [10, 35, 35, 20]
        explode = (0.05, 0.05, 0.05, 0.05)
        colours = ('#43B581', '#747F8D', '#F04747', '#FAA61A')

        plt.pie(fracs, explode=explode, autopct='%.0f%%', shadow=False, colors=colours)

        pie = BytesIO()
        plt.savefig(pie, transparent=True)
        pie.seek(0)
        plt.clf()
        plt.close()

        with Image.open('resources/pie_legend.png') as base:
            with Image.open(pie) as chart:
                base.paste(chart, box=(-100, -80), mask=chart)

            f = BytesIO()
            base.save(f, 'png')
            f.seek(0)

        return f 
Example 8
Project: jd_analysis   Author: awolfly9   File: analysis_jd_item.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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')

    # 分析购买后评论的时间分布 
Example 9
Project: SalaryClassifier   Author: rrozema12   File: diagram.py    MIT License 6 votes vote down vote up
def pie(frequencyDict, name, step):
    pyplot.figure(figsize=(20,20))

    # Create values
    ys = util.getValues(frequencyDict)
    xs = util.getKeys(frequencyDict)

    # Create plot
    pyplot.suptitle(name)
    pyplot.pie(ys, labels=xs, autopct='%1.1f%%')
    labels = [r'High School', r'Bachelors', r'masters', r'doctorate', r'dropout'
        , r'Assiciate', r'Middleschool', r'Elementary', r'Prof-school', r'other']
    pyplot.legend(labels)
    pyplot.legend(loc=2, prop={'size':15})
    pyplot.tight_layout()

    # Save plot
    filename = str(step) + '-pie-' + name + '.pdf'
    pyplot.savefig(figureFolder + filename)

    pyplot.figure() # Reset for good measure
    pyplot.close() 
Example 10
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example 11
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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"] 
Example 12
Project: TextSentimentClassification   Author: wslc1314   File: data_analysis.py    MIT License 6 votes vote down vote up
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() 
Example 13
Project: wechatAIO   Author: levoncf   File: User_API.py    GNU General Public License v3.0 6 votes vote down vote up
def gender_chart(self):
        gender_data = self.gender_calc()
        label =["Male", "Female", "Other"]
        sizes = [gender_data['male'], gender_data['female'], gender_data['other']]
        
        #Create Two plot to reflect gender distribution
        plt.subplot(1,2,1)
        x_pos = [i for i, _ in enumerate(label)]
        plt.bar(x_pos, sizes)
        plt.xticks(x_pos, label)
        plt.ylabel('numbers')
        plt.title("Gender Count")

        #pie chart
        plt.subplot(1,2,2)
        colors = ['lightskyblue', 'lightcoral', 'yellowgreen']
        #explode = (1 ,1 ,0)
        plt.pie(sizes, labels=label, colors = colors, autopct ='%1.1f%%', shadow = True)
        plt.title("Gender Distribution")
        plt.axis('equal')
        plt.show() 
Example 14
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 6 votes vote down vote up
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='图例') 
Example 15
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 16
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 17
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 18
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 6 votes vote down vote up
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='图例') 
Example 19
Project: football-scorelines   Author: pwalch   File: scorelines.py    GNU General Public License v3.0 6 votes vote down vote up
def plotResultsFrequencyPie(name, matchList):
    resultToFrequency = findResultFrequency(matchList)
    resultFrequencyPairList = sorted(resultToFrequency.items(),
                                     key=lambda resultFrequencyPair: resultFrequencyPair[0])

    pieLabels = [ resultFrequencyPair[0] for resultFrequencyPair in resultFrequencyPairList ]
    pieSizes = [ resultFrequencyPair[1] for resultFrequencyPair in resultFrequencyPairList ]
    pieColors = [ "blue", "red", "green" ]
    pyplot.figure()
    patches, textList, autoTextList = pyplot.pie(pieSizes, colors=pieColors, labels=pieLabels,
                                                 autopct="%1.1f%%", startangle=90)
    for text in textList:
        text.set_size("x-large")
    for text in autoTextList:
        text.set_size("xx-large")
    pyplot.axis("equal")
    pyplot.title("Results frequencies of " + name + " top division")
    pyplot.savefig("resultsFrequencies_" + name + ".png", dpi=200) 
Example 20
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
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') 
Example 21
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
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"] 
Example 22
Project: pie-pie-chart   Author: mmachenry   File: pie_pie_chart.py    MIT License 6 votes vote down vote up
def calibrate_scale (hx):
    input('Put known weight on the scale and then press Enter')
    reading = hx.get_data_mean()
    if reading:
        print('Mean value from HX711 subtracted by offset:', reading)
        user_input = input('Write how many grams it was and press Enter: ')
        try:
            weight = float(user_input)
            print(weight, 'grams')
        except ValueError:
            print('Expected integer or float and I have got:', user_input)

        ratio = reading / weight
        hx.set_scale_ratio(ratio)
        print('Ratio is set.')
    else:
        raise ValueError('Cannot calculate mean value.')

# Prompt user and get readings for the tare weight and full pie. 
Example 23
Project: pie-pie-chart   Author: mmachenry   File: pie_pie_chart.py    MIT License 6 votes vote down vote up
def plot_reading (hx, tare_weight, full_weight):
    while True:
        current_weight = hx.get_weight_mean(20)
        remaining_weight = max(0,current_weight - tare_weight)
        #print ("Current weight is ", current_weight, "g")

        labels = ['Remaining', 'Eaten']
        sizes = [remaining_weight, max(0,full_weight - remaining_weight)]
        colors = ['sandybrown', 'lightgrey']
        explode = (0, 0.1)
         
        title_font = { 'color':  'blue', 'weight': 'bold', 'size': 30 }
        label_font = { 'color':  'black', 'weight': 'normal', 'size': 20 }

        h = plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=180,
            textprops=label_font)

        plt.title("Pi Day Pie Pie Chart", title_font)

        plt.plot()
        plt.draw()
        plt.pause(1)
        plt.clf() 
Example 24
Project: soulmate   Author: leeyoshinari   File: dealData.py    MIT License 6 votes vote down vote up
def plot_pie(pie_values, title):
	"""
	画饼状图,并保存到本地
	:param pie_values: 字典类型
	:param title: 画出的图片标题
	"""
	label = []
	value = []
	for k, v in pie_values.items():
		label.append(k)
		value.append(v)

	explode = tuple([0.02] * len(label))
	plt.figure('title', figsize=[9.6, 7.2])
	plt.pie(value, labels=label, colors=random_color(len(label)), autopct='%.2f%%', shadow=True, explode=explode)
	plt.axis('equal')
	plt.savefig('{}.png'.format(title), bbox_inches='tight')
	plt.show() 
Example 25
Project: whatsapp_analyzer   Author: n1tr0-5urf3r   File: analyzer.py    GNU General Public License v3.0 6 votes vote down vote up
def generate_piechart(labels, values, colors, title, output, round=True):
    """Generates a piechart"""

    def absolute_value(val):
        a = np.round(val / 100. * values.sum(), 0)
        return '{0:g}'.format(float(a))

    def absolute_value_full(val):
        a = np.round(val / 100. * values.sum(), 2)
        return a

    plt.clf()
    plt.figure(figsize=(14, 7))
    if round:
        plt.pie(values, labels=labels, colors=colors,
                autopct=absolute_value, startangle=90, textprops={'fontsize': 14})
    else:
        plt.pie(values, labels=labels, colors=colors,
                autopct=absolute_value_full, startangle=90, textprops={'fontsize': 14})
    plt.title(title, fontsize=17)
    plt.axis('equal')
    plt.tight_layout()
    plt.savefig(output) 
Example 26
Project: AdOps   Author: TeddyCr   File: has_ads.txt_scraper.py    GNU General Public License v3.0 5 votes vote down vote up
def structureData(has_ads_txt, ads_txt_data, filter_status):
    """
    This function will format the data to make it readible to the user (dataframe + chart)
    """
    
    ## Create csv with data from ads.txt of filter_status == "complete" (ref runHasAdstxt())
    if filter_status == "complete":    
        labels = ["DOMAINS","SSP","PUB_ID","SALES_CHANNEL","CERT_AUTH_ID"]         
        ads_txt_data_df = pd.DataFrame.from_records(ads_txt_data, columns=labels, index=labels[0])
        ads_txt_data_df.to_csv("ads.txt_data.csv") 
    
    has_ads_txt_df = pd.DataFrame.from_dict(has_ads_txt, orient='index')
    has_ads_txt_df.columns = ["has_ads.txt"]
    
    has_ads_txt_df.to_csv("has_ads_txt.csv")

    
    temp_series = pd.Series(has_ads_txt_df['has_ads.txt'].value_counts())
    temp_dict = pd.Series.to_dict(temp_series)
    
    ## Plot pie chart of has_ads_txt df
    plt.figure(1, figsize=(4,4))
    plt.pie([v for v in temp_dict.values()], None, [k for k in temp_dict], autopct='%.2f%%',colors=['silver', 'yellow'])  ##'%.2f%% is used to format data label'
    plt.title("Has ads.txt (%tage of publishers)")
    plt.show()
    
    return "File succesfully generated." 
Example 27
Project: timetrack   Author: ravenscroftj   File: timetrack.py    MIT License 5 votes vote down vote up
def report_graph(args, echo=False):
    """Generate a bar chart report for the given timeframe."""
    start_date, end_date = parse_time_args(args)
    report_data = OrderedDict(sorted(project_report(start_date, end_date, echo).items()))

    fig = pyplot.figure()
    titleString = "Project Breakdown: {}".format(start_date.strftime("%Y-%m-%d"))

    if start_date != end_date:
        titleString+=" to {}".format(end_date.strftime("%Y-%m-%d"))

    fig.suptitle(titleString, fontsize=14, fontweight='bold')

    ax = fig.add_subplot(1,1,1)
    fig.subplots_adjust(top=0.85)
    num_reports = len(report_data)

    my_colors = ['c','m','y','r', 'g', 'b']

    for key in report_data.keys():
        report_data[key] = report_data[key]/60.0

    if args.pie:
        pyplot.axis('equal')
        pyplot.pie(report_data.values(), labels=list(report_data.keys()), autopct='%1.1f%%', colors=my_colors, startangle=90)
    else:
        ax.set_xlabel('Project')
        ax.set_ylabel('Hours')
        pyplot.bar(range(num_reports), report_data.values(), align='center', color=my_colors)
        pyplot.xticks(range(num_reports), list(report_data.keys()))

    pyplot.show() 
Example 28
Project: ikinci_duzey_plotlar   Author: lyk2018-python   File: message_counter.py    GNU General Public License v3.0 5 votes vote down vote up
def count_the_messages_by_word():
    with open("chat.txt",encoding="utf8") as f:
        text = f.readlines()
    response = requests.get(
        "http://www.turkceogretimi.com/tavsiyeler/en-%C3%A7ok-kullan%C4%B1lan-1000-t%C3%BCrk%C3%A7e-kelime")
    soup = bs4.BeautifulSoup(response.text, "lxml")
    table = soup.find("table")
    common_words = list()
    for row in table.find_all("tr")[2:50]:
        word = row.find_all("td")[1].text.strip()
        common_words.append(word)

    special_messages = ["<Media omitted>", "(file attached)", "This message was deleted", 'You deleted this message']
    n = ""
    for line in text:
        message = line.split(": ", 1)[-1]
        if all([i not in message for i in special_messages]) and all(
                [i.lower() not in message.lower().split() for i in common_words]) and message:
            n += message + " "

    message_counts = Counter([word for word in n.split() if not word.isdecimal()])
    message_counts = message_counts.most_common(25)
    data, labels = list(zip(*message_counts))
    plt.pie(data, labels=labels)
    plt.title("Most common 25 words")
    plt.show() 
Example 29
Project: ikinci_duzey_plotlar   Author: lyk2018-python   File: isimler.py    GNU General Public License v3.0 5 votes vote down vote up
def pie_chart(names,total_nums, size):     
    names = names[0:size]
    names = names[:,0]
    total_nums = total_nums[0:size]
    plt.pie(total_nums, labels=names, autopct='%1.1f%%',shadow = True,
            startangle=140)    
    plt.show()
    plt.savefig("plot1.png", dpi = 600) 
Example 30
Project: sdwan-harvester   Author: sdnewhop   File: core.py    GNU General Public License v2.0 5 votes vote down vote up
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)) 
Example 31
Project: Text-Recognition   Author: mayank-git-hub   File: profiler.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
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 
Example 32
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_default():
    # 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')
    fig1, ax1 = plt.subplots(figsize=(8, 6))
    pie1 = ax1.pie(sizes, explode=explode, labels=labels, colors=colors,
                autopct='%1.1f%%', shadow=True, startangle=90) 
Example 33
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_linewidth_0():
    # 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})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')

    # Reuse testcase from above for a labeled data test
    data = {"l": labels, "s": sizes, "c": colors, "ex": explode}
    fig = plt.figure()
    ax = fig.gca()
    ax.pie("s", explode="ex", labels="l", colors="c",
           autopct='%1.1f%%', shadow=True, startangle=90,
           wedgeprops={'linewidth': 0}, data=data)
    ax.axis('equal')

    # And again to test the pyplot functions which should also be able to be
    # called with a data kwarg
    plt.figure()
    plt.pie("s", explode="ex", labels="l", colors="c",
            autopct='%1.1f%%', shadow=True, startangle=90,
            wedgeprops={'linewidth': 0}, data=data)
    plt.axis('equal') 
Example 34
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_linewidth_2():
    # 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': 2})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 35
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_ccw_true():
    # 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,
            counterclock=True)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 36
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_rotatelabels_true():
    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Hogwarts', 'Frogs', '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,
            rotatelabels=True)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 37
Project: jd_analysis   Author: awolfly9   File: analysis_jd_item.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def analysis_buy_channel(self):
        # self.record_result('用户购买该商品使用的客户端', color = 'black', font_size = 24, strong = True)

        obj = self.data_frame['user_client_show']
        obj = obj.value_counts()
        obj = obj.rename({u'': u'其他,网页端'})
        # obj = obj.append(mobile_obj)
        # obj.plot(style = 'ro-')
        ax = obj.plot(kind = 'bar', alpha = self.opacity, color = self.color)
        ax.set_xticklabels(obj.index, rotation = 45 if len(obj.index) > 3 else 0)

        # 显示柱状图的百分比
        count = obj.sum()
        for i, val in enumerate(obj.values):
            ax.text(i - 0.25, val, '%.3f%%' % (val * 1.0 / count * 100))

        # 尝试将购买渠道和在移动端购买放到一个图中
        # plt.subplot(111)
        # 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.3, labels = obj.index)

        plt.title('该商品不同客户端的购买数量关系图')
        ax.set_xlabel('客户端')
        ax.set_ylabel('数量')

        filename = '%s_channel.png' % self.product_id
        plt.tight_layout()
        plt.savefig('%s/%s' % (utils.get_save_image_path(), filename))
        plt.clf()
        result = utils.get_image_src(filename = filename)
        self.record_result(result, type = 'image')

    # 分析购买的商品颜色 
Example 38
Project: wechat-group-ibot   Author: mobabel   File: ibot_chat_analyse.py    Apache License 2.0 5 votes vote down vote up
def gen_pie_member_gender(self, csv_file):
        df = pd.read_csv(csv_file, delimiter='\t', encoding='utf-8')

        genders = df['gender']
        col = [0, 0, 0]
        for g in genders:
            if g == 1:
                col[0] = col[0] + 1
            elif g == 2:
                col[1] = col[1] + 1
            else:
                col[2] = col[2] + 1

        perccent_male = '{0:.2f}%'.format((col[0]/len(genders) * 100))
        perccent_female = '{0:.2f}%'.format((col[1]/len(genders) * 100))
        perccent_unknown = '{0:.2f}%'.format((col[2]/len(genders) * 100))

        labels = [r'Male %s' % perccent_male,
                  r'Female %s' % perccent_female,
                  r'Unknown %s' % perccent_unknown]
        colors = ['lightskyblue', 'pink', 'gold']

        plt.figure(figsize=(8, 6))
        patches, texts = plt.pie(col, colors=colors, startangle=90)
        plt.legend(patches, labels, loc="best")
        plt.title('Gender of Member')
        # Set aspect ratio to be equal so that pie is drawn as a circle.
        plt.axis('equal')
        plt.tight_layout()

        path_image = os.path.join(self.path_analyse,
                                  '%s_member_gender_pie.png' % self.group_id)

        plt.savefig(path_image, format='png', dpi=100)
        plt.close()
        return path_image 
Example 39
Project: wechat-group-ibot   Author: mobabel   File: ibot_chat_analyse.py    Apache License 2.0 5 votes vote down vote up
def gen_pie_member_occupation(self, csv_file):
        df = pd.read_csv(csv_file, delimiter='\t', encoding='utf-8')

        branches = df['branch']
        col = [0, 0]
        for b in branches:
            if self.is_student(b):
                col[0] = col[0] + 1
            else:
                col[1] = col[1] + 1

        perccent_student = '{0:.2f}%'.format((col[0] / len(branches) * 100))
        perccent_emploee = '{0:.2f}%'.format((col[1] / len(branches) * 100))

        labels = [r'Unemployee %s' % perccent_student,
                  r'Emploee %s' % perccent_emploee]
        colors = ['forestgreen', 'royalblue']

        plt.figure(figsize=(8, 6))
        patches, texts = plt.pie(col, colors=colors, startangle=90)
        plt.legend(patches, labels, loc="best")
        plt.title('Occupation of Member')
        # Set aspect ratio to be equal so that pie is drawn as a circle.
        plt.axis('equal')
        plt.tight_layout()

        path_image = os.path.join(self.path_analyse,
                                  '%s_member_occupation_pie.png' % self.group_id)

        plt.savefig(path_image, format='png', dpi=100)
        plt.close()

        return path_image 
Example 40
Project: ImageAI   Author: OlafenwaMoses   File: video_analysis_per_second.py    MIT License 5 votes vote down vote up
def forSecond(frame_number, output_arrays, count_arrays, average_count, returned_frame):

    plt.clf()

    this_colors = []
    labels = []
    sizes = []

    counter = 0

    for eachItem in average_count:
        counter += 1
        labels.append(eachItem + " = " + str(average_count[eachItem]))
        sizes.append(average_count[eachItem])
        this_colors.append(color_index[eachItem])

    global resized

    if (resized == False):
        manager = plt.get_current_fig_manager()
        manager.resize(width=1000, height=500)
        resized = True

    plt.subplot(1, 2, 1)
    plt.title("Second : " + str(frame_number))
    plt.axis("off")
    plt.imshow(returned_frame, interpolation="none")

    plt.subplot(1, 2, 2)
    plt.title("Analysis: " + str(frame_number))
    plt.pie(sizes, labels=labels, colors=this_colors, shadow=True, startangle=140, autopct="%1.1f%%")

    plt.pause(0.01) 
Example 41
Project: ImageAI   Author: OlafenwaMoses   File: video_analysis_per_frame.py    MIT License 5 votes vote down vote up
def forFrame(frame_number, output_array, output_count, returned_frame):

    plt.clf()

    this_colors = []
    labels = []
    sizes = []

    counter = 0

    for eachItem in output_count:
        counter += 1
        labels.append(eachItem + " = " + str(output_count[eachItem]))
        sizes.append(output_count[eachItem])
        this_colors.append(color_index[eachItem])

    global resized

    if (resized == False):
        manager = plt.get_current_fig_manager()
        manager.resize(width=1000, height=500)
        resized = True

    plt.subplot(1, 2, 1)
    plt.title("Frame : " + str(frame_number))
    plt.axis("off")
    plt.imshow(returned_frame, interpolation="none")

    plt.subplot(1, 2, 2)
    plt.title("Analysis: " + str(frame_number))
    plt.pie(sizes, labels=labels, colors=this_colors, shadow=True, startangle=140, autopct="%1.1f%%")

    plt.pause(0.01) 
Example 42
Project: pyKriging   Author: capaulson   File: GlobalSensitivity.py    GNU General Public License v2.0 5 votes vote down vote up
def sensitivity_Sobol(self, Model, plot=0):
        """
        Returns the Sobol sensitivity metrics for each variable
        Input:
            Model- the name of the model given in a string 
        Output:
            Sobol- the Sobol sensitivity metrics for each variable
            plot- if 1 then a pie chart is plotted illustrating the effect of each
            variable
        """
        colors = ['lightskyblue', 'gold', 'yellowgreen', 'lightcoral']
        for i in range(self.k):
            self.dx_i[:, i] = np.gradient(self.X[:, i])
            self.denom_sum.append(np.sum((self.gamma_i[i]**2)*self.dx_i[:, i]))
        for j in range(self.k):
            self.Sobol.append(np.sum((self.gamma_i[j]**2)*self.dx_i[:, j])/sum(self.denom_sum))
        if plot == 1:
            plt.figure(figsize=(12, 8), facecolor='w', edgecolor='k', linewidth= 2.0, frameon=True)
            labels = ["S_%d" % i for i in range(1, self.k+1)]
            sizes = [i for i in self.Sobol]
            colors = [i for i in colors[0:len(labels)]]
            explode = [0.01 + 0.02 * (i % 3) for i in range(len(sizes))]
            plt.pie(sizes, labels=labels, colors=colors, explode=explode,
                    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(Model)
            plt.show()
        return self.Sobol 
Example 43
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_linewidth_0():
    # 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})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 44
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_linewidth_2():
    # 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': 2})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 45
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pie_ccw_true():
    # 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,
            counterclock=True)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 46
Project: data-science-from-scratch   Author: kevntao   File: visualizing_data.py    The Unlicense 5 votes vote down vote up
def make_chart_pie_chart(plt):

    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() 
Example 47
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pie_default():
    # 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')
    fig1, ax1 = plt.subplots(figsize=(8, 6))
    pie1 = ax1.pie(sizes, explode=explode, labels=labels, colors=colors,
                autopct='%1.1f%%', shadow=True, startangle=90) 
Example 48
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pie_linewidth_0():
    # 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})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')

    # Reuse testcase from above for a labeled data test
    data = {"l": labels, "s": sizes, "c": colors, "ex": explode}
    fig = plt.figure()
    ax = fig.gca()
    ax.pie("s", explode="ex", labels="l", colors="c",
           autopct='%1.1f%%', shadow=True, startangle=90,
           wedgeprops={'linewidth': 0}, data=data)
    ax.axis('equal')

    # And again to test the pyplot functions which should also be able to be
    # called with a data kwarg
    plt.figure()
    plt.pie("s", explode="ex", labels="l", colors="c",
            autopct='%1.1f%%', shadow=True, startangle=90,
            wedgeprops={'linewidth': 0}, data=data)
    plt.axis('equal') 
Example 49
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pie_linewidth_2():
    # 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': 2})
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 50
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pie_ccw_true():
    # 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,
            counterclock=True)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')