最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中的數(shù)據(jù)可視化matplotlib與繪圖庫模塊

 更新時間:2022年05月30日 10:48:05   作者:springsnow  
這篇文章介紹了Python中的數(shù)據(jù)可視化matplotlib與繪圖庫模塊,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

matplotlib官方文檔:https://matplotlib.org/stable/users/index.html

matplotlib是一個繪圖庫,它可以創(chuàng)建常用的統(tǒng)計圖,包括條形圖、箱型圖、折線圖、散點圖、餅圖和直方圖。

一、條形圖bar()

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')


# 修改背景為條紋
plt.style.use('ggplot')

classes = ['3班', '4班', '5班', '6班']

classes_index = range(len(classes))
print(list(classes_index))
# [0, 1, 2, 3]

student_amounts = [66, 55, 45, 70]

# 畫布設置
fig = plt.figure()
# 1,1,1表示一張畫布切割成1行1列共一張圖的第1個;2,2,1表示一張畫布切割成2行2列共4張圖的第一個(左上角)
ax1 = fig.add_subplot(1, 1, 1)
ax1.bar(classes_index, student_amounts, align='center', color='darkblue')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.xticks(classes_index,
           classes,
           rotation=0,
           fontsize=13,
           fontproperties=font)
plt.xlabel('班級', fontproperties=font, fontsize=15)
plt.ylabel('學生人數(shù)', fontproperties=font, fontsize=15)
plt.title('班級-學生人數(shù)', fontproperties=font, fontsize=20)
# 保存圖片,bbox_inches='tight'去掉圖形四周的空白
# plt.savefig('classes_students.png', dpi=400, bbox_inches='tight')
plt.show()

二、直方圖

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')

# 修改背景為條紋
plt.style.use('ggplot')
mu1, mu2, sigma = 50, 100, 10

# 構造均值為50的符合正態(tài)分布的數(shù)據(jù)
x1 = mu1 + sigma * np.random.randn(10000)
print(x1)
# [59.00855949 43.16272141 48.77109774 ... 57.94645859 54.70312714
#  58.94125528]

# 構造均值為100的符合正態(tài)分布的數(shù)據(jù)
x2 = mu2 + sigma * np.random.randn(10000)
print(x2)
# [115.19915511  82.09208214 110.88092454 ...  95.0872103  104.21549068
#  133.36025251]

fig = plt.figure()
ax1 = fig.add_subplot(121)
# bins=50表示每個變量的值分成50份,即會有50根柱子
ax1.hist(x1, bins=50, color='darkgreen')

ax2 = fig.add_subplot(122)
ax2.hist(x2, bins=50, color='orange')

fig.suptitle('兩個正態(tài)分布', fontproperties=font, fontweight='bold', fontsize=15)
ax1.set_title('綠色的正態(tài)分布', fontproperties=font)
ax2.set_title('橙色的正態(tài)分布', fontproperties=font)
plt.show()

三、折線圖

import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')

# 修改背景為條紋
plt.style.use('ggplot')

np.random.seed(1)

# 使用numpy的累加和,保證數(shù)據(jù)取值范圍不會在(0,1)內(nèi)波動
plot_data1 = randn(40).cumsum()
print(plot_data1)
# [ 1.62434536  1.01258895  0.4844172  -0.58855142  0.2768562  -2.02468249
#  -0.27987073 -1.04107763 -0.72203853 -0.97140891  0.49069903 -1.56944168
#  -1.89185888 -2.27591324 -1.1421438  -2.24203506 -2.41446327 -3.29232169
#  -3.25010794 -2.66729273 -3.76791191 -2.6231882  -1.72159748 -1.21910314
#  -0.31824719 -1.00197505 -1.12486527 -2.06063471 -2.32852279 -1.79816732
#  -2.48982807 -2.8865816  -3.5737543  -4.41895994 -5.09020607 -5.10287067
#  -6.22018102 -5.98576532 -4.32596314 -3.58391898]

plot_data2 = randn(40).cumsum()
plot_data3 = randn(40).cumsum()
plot_data4 = randn(40).cumsum()

plt.plot(plot_data1, marker='o', color='red', linestyle='-', label='紅實線')
plt.plot(plot_data2, marker='x', color='orange', linestyle='--', label='橙虛線')
plt.plot(plot_data3, marker='*', color='yellow', linestyle='-.', label='黃點線')
plt.plot(plot_data4, marker='s', color='green', linestyle=':', label='綠點圖')

# loc='best'給label自動選擇最好的位置
plt.legend(loc='best', prop=font)
plt.show()

四、散點圖+直線圖

import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')

# 修改背景為條紋
plt.style.use('ggplot')

x = np.arange(1, 20, 1)
print(x)
# [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

# 擬合一條水平散點線
np.random.seed(1)
y_linear = x + 10 * np.random.randn(19)
# print(y_linear)
# [ 17.24345364  -4.11756414  -2.28171752  -6.72968622  13.65407629
#  -17.01538697  24.44811764   0.38793099  12.19039096   7.50629625
#   25.62107937  -8.60140709   9.77582796  10.15945645  26.33769442
#    5.00108733  15.27571792   9.22141582  19.42213747]

# 擬合一條x2的散點線
y_quad = x**2 + 10 * np.random.randn(19)
print(y_quad)
# [  6.82815214  -7.00619177  20.4472371   25.01590721  30.02494339
#   45.00855949  42.16272141  62.77109774  71.64230566  97.3211192
#  126.30355467 137.08339248 165.03246473 189.128273   216.54794359
#  249.28753869 288.87335401 312.82689651 363.34415698]

# s是散點大小
fig = plt.figure()
ax1 = fig.add_subplot(121)
plt.scatter(x, y_linear, s=30, color='r', label='藍點')
plt.scatter(x, y_quad, s=100, color='b', label='紅點')

ax2 = fig.add_subplot(122)
plt.plot(x, y_linear, color='r')
plt.plot(x, y_quad, color='b')

# 限制x軸和y軸的范圍取值
plt.xlim(min(x) - 1, max(x) + 1)
plt.ylim(min(y_quad) - 10, max(y_quad) + 10)
fig.suptitle('散點圖+直線圖', fontproperties=font, fontsize=20)
ax1.set_title('散點圖', fontproperties=font)
ax1.legend(prop=font)
ax2.set_title('直線圖', fontproperties=font)
plt.show()

五、餅圖

import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')


mpl.rcParams['font.sans-serif'] = ['SimHei']

fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))

recipe = ['優(yōu)', '良', '輕度污染', '中度污染', '重度污染', '嚴重污染', '缺']

data = [2, 49, 21, 9, 11, 6, 2]
colors = ['lime', 'yellow', 'darkorange', 'red', 'purple', 'maroon', 'grey']
wedges, texts, texts2 = ax.pie(data,
                               wedgeprops=dict(width=0.5),
                               startangle=40,
                               colors=colors,
                               autopct='%1.0f%%',
                               pctdistance=0.8)
plt.setp(texts2, size=14, weight="bold")

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(xycoords='data',
          textcoords='data',
          arrowprops=dict(arrowstyle="->"),
          bbox=None,
          zorder=0,
          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))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i],
                xy=(x, y),
                xytext=(1.25 * np.sign(x), 1.3 * y),
                size=16,
                horizontalalignment=horizontalalignment,
                fontproperties=font,
                **kw)

ax.set_title("餅圖示例", fontproperties=font)

plt.show()
# plt.savefig('jiaopie2.png')

六、箱型圖

箱型圖:又稱為盒須圖、盒式圖、盒狀圖或箱線圖,是一種用作顯示一組數(shù)據(jù)分散情況資料的統(tǒng)計圖(在數(shù)據(jù)分析中常用在異常值檢測)

包含一組數(shù)據(jù)的:最大值、最小值、中位數(shù)、上四分位數(shù)(Q3)、下四分位數(shù)(Q1)、異常值

  • 中位數(shù) →一組數(shù)據(jù)平均分成兩份,中間的數(shù)
  • 上四分位數(shù)Q1 →是將序列平均分成四份,計算(n+1)/4與(n-1)/4兩種,一般使用(n+1)/4
  • 下四分位數(shù)Q3 →是將序列平均分成四份,計算(1+n)/4*3=6.75
  • 內(nèi)限 →T形的盒須就是內(nèi)限,最大值區(qū)間Q3+1.5IQR,最小值區(qū)間Q1-1.5IQR (IQR=Q3-Q1)
  • 外限 →T形的盒須就是內(nèi)限,最大值區(qū)間Q3+3IQR,最小值區(qū)間Q1-3IQR (IQR=Q3-Q1)
  • 異常值 →內(nèi)限之外 - 中度異常,外限之外 - 極度異常
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
plt.figure(figsize=(10, 4))
# 創(chuàng)建圖表、數(shù)據(jù)

f = df.boxplot(
    sym='o',  # 異常點形狀,參考marker
    vert=True,  # 是否垂直
    whis=1.5,  # IQR,默認1.5,也可以設置區(qū)間比如[5,95],代表強制上下邊緣為數(shù)據(jù)95%和5%位置
    patch_artist=True,  # 上下四分位框內(nèi)是否填充,True為填充
    meanline=False,
    showmeans=True,  # 是否有均值線及其形狀
    showbox=True,  # 是否顯示箱線
    showcaps=True,  # 是否顯示邊緣線
    showfliers=True,  # 是否顯示異常值
    notch=False,  # 中間箱體是否缺口
    return_type='dict'  # 返回類型為字典
)
plt.title('boxplot')

for box in f['boxes']:
    box.set(color='b', linewidth=1)  # 箱體邊框顏色
    box.set(facecolor='b', alpha=0.5)  # 箱體內(nèi)部填充顏色
for whisker in f['whiskers']:
    whisker.set(color='k', linewidth=0.5, linestyle='-')
for cap in f['caps']:
    cap.set(color='gray', linewidth=2)
for median in f['medians']:
    median.set(color='DarkBlue', linewidth=2)
for flier in f['fliers']:
    flier.set(marker='o', color='y', alpha=0.5)
# boxes, 箱線
# medians, 中位值的橫線,
# whiskers, 從box到error bar之間的豎線.
# fliers, 異常值
# caps, error bar橫線
# means, 均值的橫線
plt.show()

七、plot函數(shù)參數(shù)

  • 線型linestyle(-,-.,--,..)
  • 點型marker(v,^,s,*,H,+,x,D,o,…)
  • 顏色color(b,g,r,y,k,w,…)

八、圖像標注參數(shù)

  • 設置圖像標題:plt.title()
  • 設置x軸名稱:plt.xlabel()
  • 設置y軸名稱:plt.ylabel()
  • 設置X軸范圍:plt.xlim()
  • 設置Y軸范圍:plt.ylim()
  • 設置X軸刻度:plt.xticks()
  • 設置Y軸刻度:plt.yticks()
  • 設置曲線圖例:plt.legend()

九、Matplolib應用

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc')


header_list = ['方程組', '函數(shù)', '導數(shù)', '微積分', '線性代數(shù)', '概率論', '統(tǒng)計學']
py3_df = pd.read_excel('py3.xlsx', header=None,   skiprows=[0, 1], names=header_list)
# 處理帶有NaN的行
py3_df = py3_df.dropna(axis=0) #
print(py3_df)

# 自定義映射
map_dict = {
    '不會': 0,
    '了解': 1,
    '熟悉': 2,
    '使用過': 3,
}

for header in header_list:
    py3_df[header] = py3_df[header].map(map_dict)

unable_series = (py3_df == 0).sum(axis=0)
know_series = (py3_df == 1).sum(axis=0)
familiar_series = (py3_df == 2).sum(axis=0)
use_series = (py3_df == 3).sum(axis=0)

unable_label = '不會'
know_label = '了解'
familiar_label = '熟悉'
use_label = '使用過'
for i in range(len(header_list)):
    bottom = 0

    # 描繪不會的條形圖
    plt.bar(x=header_list[i], height=unable_series[i],  width=0.60, color='r', label=unable_label)
    if unable_series[i] != 0:
        plt.text(header_list[i], bottom, s=unable_series[i],   ha='center', va='bottom', fontsize=15, color='white')
    bottom += unable_series[i]

    # 描繪了解的條形圖
    plt.bar(x=header_list[i], height=know_series[i],  width=0.60, color='y', bottom=bottom, label=know_label)
    if know_series[i] != 0:
        plt.text(header_list[i], bottom, s=know_series[i],  ha='center', va='bottom', fontsize=15, color='white')
    bottom += know_series[i]

    # 描繪熟悉的條形圖
    plt.bar(x=header_list[i], height=familiar_series[i],    width=0.60, color='g', bottom=bottom, label=familiar_label)
    if familiar_series[i] != 0:
        plt.text(header_list[i], bottom, s=familiar_series[i], ha='center', va='bottom', fontsize=15, color='white')
    bottom += familiar_series[i]

    # 描繪使用過的條形圖
    plt.bar(x=header_list[i], height=use_series[i],  width=0.60, color='b', bottom=bottom, label=use_label)
    if use_series[i] != 0:
        plt.text(header_list[i], bottom, s=use_series[i], ha='center', va='bottom', fontsize=15, color='white')

    unable_label = know_label = familiar_label = use_label = ''

plt.xticks(header_list, fontproperties=font)
plt.ylabel('人數(shù)', fontproperties=font)
plt.title('Python3期數(shù)學摸底可視化', fontproperties=font)
plt.legend(prop=font, loc='upper left')
plt.show()

 

    方程組   函數(shù)   導數(shù)        微積分       線性代數(shù)  概率論  統(tǒng)計學
0   使用過  使用過   不會         不會         不會   不會   不會
1   使用過  使用過   了解         不會         不會   不會   不會
2   使用過  使用過   熟悉         不會         不會   不會   不會
3    熟悉   熟悉   熟悉         了解         了解   了解   了解
4   使用過  使用過  使用過        使用過        使用過  使用過  使用過
5   使用過  使用過  使用過         不會         不會   不會   了解
6    熟悉   熟悉   熟悉         熟悉         熟悉   熟悉   不會
7   使用過  使用過  使用過        使用過        使用過  使用過  使用過
8    熟悉   熟悉   熟悉         熟悉         熟悉  使用過  使用過
9    熟悉   熟悉  使用過         不會        使用過  使用過   不會
10  使用過  使用過   熟悉         熟悉         熟悉   熟悉   熟悉
11  使用過  使用過  使用過        使用過        使用過   不會   不會
12  使用過  使用過  使用過        使用過        使用過  使用過  使用過
13  使用過  使用過   了解         不會         不會   不會   不會
14  使用過  使用過  使用過        使用過        使用過   不會   不會
15  使用過  使用過   熟悉         不會         不會   不會   不會
16   熟悉   熟悉  使用過        使用過        使用過   不會   不會
17  使用過  使用過  使用過         了解         不會   不會   不會
18  使用過  使用過  使用過        使用過         熟悉   熟悉   熟悉
19  使用過  使用過  使用過         了解         不會   不會   不會
20  使用過  使用過  使用過        使用過        使用過  使用過  使用過
21  使用過  使用過  使用過        使用過        使用過  使用過  使用過
22  使用過  很了解   熟悉  了解一點,不會運用  了解一點,不會運用   了解   不會
23  使用過  使用過  使用過        使用過         熟悉  使用過   熟悉
24   熟悉   熟悉   熟悉        使用過         不會   不會   不會
25  使用過  使用過  使用過        使用過        使用過  使用過  使用過
26  使用過  使用過  使用過        使用過        使用過   不會   不會
27  使用過  使用過   不會         不會         不會   不會   不會
28  使用過  使用過  使用過        使用過        使用過  使用過   了解
29  使用過  使用過  使用過        使用過        使用過   了解   不會
30  使用過  使用過  使用過        使用過        使用過   不會   不會
31  使用過  使用過  使用過        使用過         不會  使用過  使用過
32   熟悉   熟悉  使用過        使用過        使用過   不會   不會
33  使用過  使用過  使用過        使用過         熟悉  使用過   熟悉
34   熟悉   熟悉   熟悉        使用過        使用過   熟悉   不會
35  使用過  使用過  使用過        使用過        使用過  使用過  使用過
36  使用過  使用過  使用過        使用過        使用過  使用過   了解
37  使用過  使用過  使用過        使用過        使用過   不會   不會
38  使用過  使用過  使用過         不會         不會   不會   不會
39  使用過  使用過   不會         不會         不會   不會   不會
40  使用過  使用過  使用過        使用過        使用過   不會   不會
41  使用過  使用過   熟悉         了解         了解   了解   不會
42  使用過  使用過  使用過         不會         不會   不會   不會
43   熟悉  使用過   了解         了解         不會   不會   不會

到此這篇關于Python中數(shù)據(jù)可視化matplotlib與繪圖庫模塊的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 使用Python將JSON,XML和YAML數(shù)據(jù)寫入Excel文件

    使用Python將JSON,XML和YAML數(shù)據(jù)寫入Excel文件

    JSON、XML和YAML作為主流結構化數(shù)據(jù)格式,因其層次化表達能力和跨平臺兼容性,已成為系統(tǒng)間數(shù)據(jù)交換的通用載體,本文將介紹如何使用Python導入JSON、XML和YAML格式數(shù)據(jù)到Excel文件中,需要的可以參考下
    2025-04-04
  • python實現(xiàn)自動登錄12306自動搶票功能

    python實現(xiàn)自動登錄12306自動搶票功能

    隨著互聯(lián)網(wǎng)技術的發(fā)展,越來越多的人選擇通過網(wǎng)絡平臺購票,特別是在中國,12306作為官方火車票預訂平臺,承擔了巨大的訪問量,對于熱門線路或者節(jié)假日出行,往往會出現(xiàn)一票難求的情況,因此,一些技術愛好者嘗試利用編程語言如Python來開發(fā)搶票腳本
    2025-01-01
  • Python數(shù)據(jù)結構之循環(huán)鏈表詳解

    Python數(shù)據(jù)結構之循環(huán)鏈表詳解

    循環(huán)鏈表 (Circular Linked List) 是鏈式存儲結構的另一種形式,它將鏈表中最后一個結點的指針指向鏈表的頭結點,使整個鏈表頭尾相接形成一個環(huán)形,使鏈表的操作更加方便靈活。本文將詳細介紹一下循環(huán)鏈表的相關知識,需要的可以參考一下
    2022-01-01
  • pygame學習筆記(1):矩形、圓型畫圖實例

    pygame學習筆記(1):矩形、圓型畫圖實例

    這篇文章主要介紹了pygame學習筆記(1):矩形、圓型畫圖實例,本文講解了pygame窗口、窗口退出、pygame中的顏色、圓形、矩形及一個完整實例,需要的朋友可以參考下
    2015-04-04
  • python遞歸算法(無限遞歸,正常遞歸,階乘)

    python遞歸算法(無限遞歸,正常遞歸,階乘)

    本文主要介紹了python遞歸算法,包含無限遞歸,正常遞歸,階乘等,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-02-02
  • python采集百度百科的方法

    python采集百度百科的方法

    這篇文章主要介紹了python采集百度百科的方法,涉及Python正則匹配及頁面抓取的相關技巧,需要的朋友可以參考下
    2015-06-06
  • python 中文件輸入輸出及os模塊對文件系統(tǒng)的操作方法

    python 中文件輸入輸出及os模塊對文件系統(tǒng)的操作方法

    這篇文章主要介紹了python 中文件輸入輸出及os模塊對文件系統(tǒng)的操作方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-08-08
  • Python cookbook(數(shù)據(jù)結構與算法)實現(xiàn)優(yōu)先級隊列的方法示例

    Python cookbook(數(shù)據(jù)結構與算法)實現(xiàn)優(yōu)先級隊列的方法示例

    這篇文章主要介紹了Python cookbook(數(shù)據(jù)結構與算法)實現(xiàn)優(yōu)先級隊列的方法,結合實例形式分析了Python中基于給定優(yōu)先級進行隊列元素排序的相關操作技巧,需要的朋友可以參考下
    2018-02-02
  • python查看包版本、更新單個包、卸載單個包的操作方法

    python查看包版本、更新單個包、卸載單個包的操作方法

    這篇文章主要介紹了python查看包版本、更新單個包、卸載單個包,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-12-12
  • 如何在Django項目中引入靜態(tài)文件

    如何在Django項目中引入靜態(tài)文件

    這篇文章主要介紹了如何在Django項目中引入靜態(tài)文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07

最新評論

藁城市| 高邑县| 翁源县| 贵州省| 松江区| 洪泽县| 磴口县| 陈巴尔虎旗| 沙田区| 友谊县| 宁强县| 周口市| 东乌珠穆沁旗| 岳阳市| 赤水市| 抚松县| 沁水县| 武功县| 招远市| 健康| 揭西县| 普宁市| 凌海市| 马尔康县| 新乡县| 邹平县| 绥中县| 博爱县| 越西县| 嘉义县| 盘锦市| 石台县| 全州县| 通山县| 郁南县| 惠州市| 古交市| 陈巴尔虎旗| 淄博市| 青阳县| 法库县|