精华内容
下载资源
问答
  • Matplotlib饼图注释

    2021-01-07 10:22:33
    import matplotlib.pyplot as plt plt.figure(figsize=(9,9)) # 环形饼图元素 recipe = ["225g flour", "90g sugar", "1 egg", "60g butter", "100ml milk", "1/2package of yeast"] # ⽐例 data = [225, 90
    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(9,9))
    
    # 环形饼图元素
    recipe = ["225g flour",
              "90g sugar",
              "1 egg",
              "60g butter",
              "100ml milk",
              "1/2package of yeast"]
    
    # ⽐例
    data = [225, 90, 50, 60, 100, 5]
    
    wedges, texts = plt.pie(data,startangle=40)
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    
    kw = dict(arrowprops=dict(arrowstyle="-"),
              bbox=bbox_props,va="center")
    
    for i, p in enumerate(wedges):
        ang = (p.theta2 - p.theta1)/2. + p.theta1 # ⻆度计算
        
        # ⻆度转弧度----->弧度转坐标
        y = np.sin(np.deg2rad(ang))
        x = np.cos(np.deg2rad(ang))
        ha = {-1: "right", 1: "left"}[int(np.sign(x))] # ⽔平对⻬⽅式
        connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 箭头连接样式
        kw["arrowprops"].update({"connectionstyle": connectionstyle}) # 更新箭头连接⽅式
        plt.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                     ha=ha,**kw,fontsize = 18,weight = 'bold')
        
    plt.title("Matplotlib bakery: A donut",fontsize = 18,pad = 25)
    plt.tight_layout()
    

    image-20210106170015184

    展开全文
  • 填写自己的mysql连接方式和sql语句即可实现饼图带百分比,线长度自己可以调参数 import pymysql from matplotlib import pyplot as plt import numpy as np class mysql_func(): # 配置mysql数据库连接池 def init...

    填写自己的mysql连接方式和sql语句即可实现饼图带百分比,线长度自己可以调参数
    import pymysql
    from matplotlib import pyplot as plt

    import numpy as np

    class mysql_func():
    # 配置mysql数据库连接池
    def init(self, host=’’, user=’’, password=’’, port=, database=’’,
    charset=’’):
    self.host = host
    self.user = user
    self.password = password
    self.port = port
    self.database = database
    self.charset = charset
    self.db = pymysql.connect(host=host, user=user, password=password, port=port, database=database,
    charset=charset)

    # 取数据,tuple类型返回
    def get_data(self, sql):
        self.curors = self.db.cursor()
        self.curors.execute(sql)
        self.db.commit()
        data = self.curors.fetchall()
        self.curors.close()
        return data
    
    # 存数据,int类型返回成功条数
    def get_row_number(self, sql, data=None):
        self.curors = self.db.cursor()
        if data is None or len(data) == 0:
            self.curors.execute(sql)
        else:
            if type(data[0]) != type([]):
                data = [data]
            self.curors.executemany(sql, data)
        self.db.commit()
        data = self.curors.rowcount
        self.curors.close()
        return data
    
    # 取数据,[dict]类型返回
    def get_json(self, sql):
        self.curors = self.db.cursor()
        self.curors.execute(sql)
        self.db.commit()
        columns = [col[0] for col in self.curors.description]
        data = [dict(zip(columns, row)) for row in self.curors.fetchall()]
        self.curors.close()
        return data
    

    def academic_co_country_img():
    mysql_aliyun = mysql_func(host=’’, user=’’, password=’’, port=,
    database=’’)
    sql = ‘’’’’’
    country_data = mysql_aliyun.get_data(sql)
    print(country_data)
    fig, ax = plt.subplots(figsize=(10, 6), subplot_kw=dict(aspect=“equal”))
    size = 0.3
    vals = np.array([[k[1],0] for k in country_data])
    # print(vals.sum())
    ingredients = [k[0] for k in country_data]
    print(ingredients)
    recipe = []
    for k in country_data:
    recipe.append(k[1]/vals.sum())
    # recipe.append(format(k[1]/vals.sum(),’.1%’))
    # print(recipe)
    new_ingredients = []
    for l in range(len(ingredients)):
    new_ingredients.append(ingredients[l] + " " + str(format(recipe[l],’.1%’)))
    print(new_ingredients)

    new_data = []
    qita_num = 0
    data = [k[1] for k in country_data]
    if len(data) >= 10:
        for d in range(len(data)):
            if d > 9:
                new_data.append(data[d])
                qita_num += data[d]
        new_data.append(qita_num)
    else:
        new_data = data
    print(new_data,"************************")
    wedges, texts = ax.pie(data, wedgeprops=dict(width=0.3), startangle=-40)
    ax.legend(new_ingredients, title="", loc="upper left", bbox_to_anchor=(1, 0, 0.5, 1), )
    
    # 每一类别说明框
    # boxstyle框的类型,fc填充颜色,ec边框颜色,lw边框宽度
    bbox_props = dict(boxstyle="square,pad=0.3", fc='white', ec="white", lw=0.72)
    # 设置框引出方式
    kw = dict(arrowprops=dict(arrowstyle="-"),
              bbox=bbox_props, zorder=0, va="center")
    
    # 添加标签
    ta = 1.4
    for i, p in enumerate(wedges):
        # if recipe[i] >= 0.03:
        if i < 10:
            ang = (p.theta2 - p.theta1) / 2. + p.theta1
            y = np.sin(np.deg2rad(ang))
            x = np.cos(np.deg2rad(ang))
            # 设置方向
            horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
            connectionstyle = "angle,angleA=0,angleB={}".format(ang)
            kw["arrowprops"].update({"connectionstyle": connectionstyle})
            #设置标注 这一步可以调整饼图的线
            ax.annotate(format(recipe[i],'.1%'), xy=(x, y), xytext=(1.35 * np.sign(x), 1.4 * y),
                        horizontalalignment=horizontalalignment, color='black', **kw)
            ta -= 0.3
    
    ax.set_title("    ")
    
    plt.show()
    '''
    cmap = plt.get_cmap("tab20c")
    outer_colors = cmap(np.arange(3) * 4)
    
    wedges = ax.pie(vals.sum(axis=1), wedgeprops=dict(width=0.5), startangle=-40, autopct='%.1f%%',radius=1, pctdistance=1.2, labeldistance=1.2)
    
    ax.legend(ingredients, title="", loc="upper left", bbox_to_anchor=(1, 0, 0.5, 1),)
    
    ax.set(aspect="equal", title='')
    plt.show()
    '''
    

    if name == ‘main’:
    academic_co_country_img()

    展开全文
  • I have produced a very simple pie chart in Python using Matplotlib and I am wanting to edit the alignment of my labels. I have used \n within my labels to split the line as the labels are too long for...

    I have produced a very simple pie chart in Python using Matplotlib and I am wanting to edit the alignment of my labels. I have used \n within my labels to split the line as the labels are too long for one line. But as you can see from the picture called 'pie chart image', it's a mix of weird alignments at the moment. I would really like to have it center alignment.

    For other chart/graph types in Matplotlib there is an argument called align where you can set it to center, however, plt.pie(...) does not seem to have this attribute.

    Here is my code:

    import matplotlib.pyplot as plt

    k = [7,15]

    labels = 'Strongly and Mostly \n Agree', 'Strongly/Mostly Disagree \n and In the Middle'

    plt.pie(k, labels= labels)

    plt.show()

    a4558f082c4027d2d1a9c994cd374eb5.png

    Any ideas?

    解决方案

    You can pass a dictionary of text properties to plt.pie via the textprops argument. For example:

    plt.pie(k, labels=labels, textprops={'weight': 'bold'})

    However, if you try to specify the horizontalalignment property, you'll get an error saying that you provided that parameter twice. Obviously you didn't, but matplotlib passed both it's hard-coded value and your value to some internal function.

    But that's probably a good thing. The way I see it, there's not so much a mix of alignments, but a consistent alignment of the text against the pie.

    Back to your question

    pie returns both the patches and the labels for each wedge. So you can loop through the labels after your initial call to pie to modify their alignment. That looks like this:

    k = [7, 15]

    labels = 'Strongly and Mostly\nAgree', 'Strongly/Mostly Disagree\nand In the Middle'

    fig, ax = plt.subplots()

    ax.set_aspect('equal')

    wedges, labels = ax.pie(k, labels=labels, textprops={'weight': 'bold'})

    for label in labels:

    label.set_horizontalalignment('center')

    4aT0f.png

    As you can see, the labels now overlap with the wedges, diminishing legibility.

    The labels also have a set_position method (i.e., label.set_position((x, y))), but recomputing the positions for N labels in a pie chart sounds like a Bad Time to me.

    展开全文
  • 改变饼图使用autopct设置百分比显示后的位置 可以看到环状图上的百分比数字位置显示看的很不舒服,想让数据离中心远一点 在pie中使用pctdistance参数

    改变饼图使用autopct设置百分比显示后的位置

    在这里插入图片描述

    可以看到环状图上的百分比数字位置显示看的很不舒服,想让数据离中心远一点

    在pie中使用pctdistance参数

    在这里插入图片描述

    在这里插入图片描述

    展开全文
  • 在使用Matplotlib 绘制饼图的时候有些时候一些数据的比列太小在饼图呈现的效果不明显 很容易被覆盖,为了解决这个问题以下就是我个人的心得。 【未解决之前呈现的效果】 可以看到这个饼状图其他和硕士这2个部分占比...
  • 我在饼图中添加了旋转标签,并希望默认情况下标签将位于饼图的每个扇区的中心。但事实并非如此如何将标签居中?在这里是我的后端代码:from PyQt5 import QtCore, QtGui, QtWidgetsimport sysfrom PyQt5.QtWidgets ...
  • 解决方案 Alternatively you can put the legends beside the pie graph: import matplotlib.pyplot as plt import numpy as np x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct',...
  • 或者,可以将图例放在饼图旁边:import matplotlib.pyplot as pltimport numpy as npx = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])y = np.array([234, 64, 54,10...
  • 我试图在matplotlib中创建一个饼图,并希望将标签放在楔形内.我使用以下代码来执行此操作:import matplotlib.pyplot as pltfig = plt.figure(1, figsize=(8,8), dpi=60)ax=fig.add_axes([0.1,0.1,0.8,0.8])labels = ...
  • #Pie for Life Expectancy in Boroughs import pandas as pd import matplotlib import matplotlib.pyplot as plt # show plots inline %matplotlib inline # use ggplot style matplotlib.style.use('ggplot') #...
  • 不只是饼状图,Matplotlb的官网上Example页面下有各种图表的例子(Matplotlib-Examples),因此,如果想要绘制图表,建议先到官网上看一看,挑选合适的图表,如果不懂的话,再找其他资料学习。 最近需要绘制饼状图...
  • Matplotlib饼图显示部分数据标签

    千次阅读 2020-08-18 23:16:49
    调用下面的my_autopct def my_autopct(pct): return ('%.2f' % pct) if pct > 20 else '' ax.pie(df[col], labels=df.index, autopct=my_autopct, colors=colors) ...
  • 使用autopct关键字我们知道显示的百分比乘以所有实际值的总和必须是实际值,我们可以将其定义为函数,并使用autopct关键字将此函数提供给plt.pie.import matplotlib.pyplot as pltimport numpylabels = 'Frogs', 'Hogs...
  • pandas-matplotlib饼图

    2018-12-12 17:42:25
    # -*-coding:utf-8 -*- ...import matplotlib.pyplot as plt students = pd.read_excel(&quot;C:/Users/asus/Downloads/pandas/012/Students.xlsx&quot;,index_col='From') print(students) students['2017...
  • 我在使用matplotlib设置饼图时遇到了一个奇怪的问题。由于某些原因,它似乎没有正确地处理我的labels参数。在一点背景知识…我正在开发一个工具,它将允许我们创建汇总web地图服务点击率的表格。这基本上只是遍历...
  • matplotlib饼图

    2019-01-20 17:47:45
  • 在tkinter主界面嵌入matplotlib饼图

    千次阅读 2020-03-14 16:14:04
    在主窗口的指定区域嵌入饼图,代码如下(python3.7): import tkinter import matplotlib from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt plt.rcParams[...
  • 饼图(pie)1 饼图介绍饼图广泛得应用在各个领域,用于表示不同分类的占比情况,通过弧度大小来对比各种分类。饼图通过将一个圆饼按照分类的占比划分成多个区块,整个圆饼代表数据的总量,每个区块(圆弧)表示该分类占...
  • 所以你可以通过乘以饼图的总大小并除以100来将百分比转回原始值: figure(1, figsize=(6,6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, 45, 10] total = sum...
  • python+matplotlib 饼图

    2019-06-30 15:32:08
    python+matplotlib 饼图https://blog.csdn.net/crisschan/article/details/71107010
  • matplotlib 饼图绘制

    千次阅读 2017-12-08 13:50:11
    matplotlib.pyplot as plt # 设置绘图的主题风格(不妨使用R中的ggplot分隔) plt.style.use( 'ggplot' ) # 构造数据 edu = [ 0.2515 , 0.3724 , 0.3336 , 0.0368 , 0.0057 ] labels = [ '中专' , '大专' , ...
  • Matplotlib 饼图

    2019-10-28 12:21:26
    章节Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 ... Matplotlib 饼图 Matplotlib 直方图 Matplotlib 散点图 Matplotlib 填充图 Matplotlib 网格 Matplot...
  • 定制Matplotlib使用样式表和rcParams 自定义Matplotlib的属性和默认样式的提示。 使用样式表 该style软件包增加了对易于切换绘图“样式”的支持,其参数与 matplotlib rc文件(在启动时读取以配置matplotlib)相同。...
  • Python matplotlib绘制饼图

    千次阅读 2020-11-14 01:06:35
    Python matplotlib绘制饼图
  • matplotlib.pyplot 中还有一种图表用于直观表示占比情况的饼图,在matplotlib官网上也列举出非常多关于饼图的案例。 本期,我们将详细学习matplotlib 绘制饼图相关属性的学习,let's go~ 1. 等高线图概述 ...
  • Matplotlib饼图与嵌套图

    千次阅读 2018-09-24 23:15:10
    饼图pie import matplotlib.pyplot as plt import numpy as np %matplotlib inline m = 51212 f = 40732 m_perc = m/(m+f) f_perc = f/(m+f) colors = ['navy','lightcoral'] labels = ['Male','Female'] plt....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 9,607
精华内容 3,842
关键字:

matplotlib饼图