python作圖的實(shí)例

首先導(dǎo)入模塊

import numpy as np

import matplotlib

import matplotlib.mlab as mlab

import matplotlib.pyplot as plt

import matplotlib.font_manager as fm

from mpl_toolkits.mplot3d import Axes3D

解決中文亂碼問題


# 解決中文亂碼問題

plt.rcParams['font.sans-serif']=[u'simHei']

plt.rcParams['axes.unicode_minus']=False

1霜幼、簡單曲線圖


def simple_plot():

? ? """

? ? simple plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? x = np.linspace(-np.pi, np.pi, 256, endpoint=True)

? ? y_cos, y_sin = np.cos(x), np.sin(x)

? ? # 生成畫布罗标,并設(shè)定標(biāo)題

? ? plt.figure(figsize=(8, 6), dpi=80)

? ? plt.title("簡單曲線圖")

? ? plt.grid(True)

? ? # 設(shè)置X軸

? ? plt.xlabel("X軸")

? ? plt.xlim(-4.0, 4.0)

? ? plt.xticks(np.linspace(-4, 4, 9, endpoint=True))

? ? # 設(shè)置Y軸

? ? plt.ylabel("Y軸")

? ? plt.ylim(-1.0, 1.0)

? ? plt.yticks(np.linspace(-1, 1, 9, endpoint=True))

? ? # 畫兩條曲線

? ? plt.plot(x, y_cos, "b--", linewidth=2.0, label="cos示例")

? ? plt.plot(x, y_sin, "g-", linewidth=2.0, label="sin示例")

? ? # 設(shè)置圖例位置,loc可以為[upper, lower, left, right, center]

? ? plt.legend(loc="upper left",shadow=True)

? ? # 圖形顯示

? ? plt.show()

? ? return

simple_plot()

2第焰、復(fù)雜曲線圖,雙y軸

def simple_advanced_plot():

? ? """

? ? simple advanced plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? x = np.linspace(-np.pi, np.pi, 256, endpoint=True)

? ? y_cos, y_sin = np.cos(x), np.sin(x)

? ? # 生成畫布, 并設(shè)定標(biāo)題

? ? plt.figure(figsize=(8, 6), dpi=80)

? ? plt.title("復(fù)雜曲線圖")

? ? plt.grid(True)

? ? # 畫圖的另外一種方式

? ? ax_1 = plt.subplot(111)

? ? ax_1.plot(x, y_cos, color="blue", linewidth=2.0, linestyle="--", label="左cos")

? ? ax_1.legend(loc="upper left", shadow=True)

? ? # 設(shè)置Y軸(左邊)

? ? ax_1.set_ylabel("左cos的y軸")

? ? ax_1.set_ylim(-1.0, 1.0)

? ? ax_1.set_yticks(np.linspace(-1, 1, 9, endpoint=True))

? ? # 畫圖的另外一種方式

? ? ax_2 = ax_1.twinx()

? ? ax_2.plot(x, y_sin, color="green", linewidth=2.0, linestyle="-", label="右sin")

? ? ax_2.legend(loc="upper right", shadow=True)

? ? # 設(shè)置Y軸(右邊)

? ? ax_2.set_ylabel("右sin的y軸")

? ? ax_2.set_ylim(-2.0, 2.0)

? ? ax_2.set_yticks(np.linspace(-2, 2, 9, endpoint=True))

? ? # 設(shè)置X軸(共同)

? ? ax_1.set_xlabel("x軸")

? ? ax_1.set_xlim(-4.0, 4.0)

? ? ax_1.set_xticks(np.linspace(-4, 4, 9, endpoint=True))

? ? # 圖形顯示

? ? plt.show()

? ? return

simple_advanced_plot()


3掷邦、子圖顯示

def subplot_plot():

? ? """

? ? subplot plot

? ? """

? ? # 子圖的style列表

? ? style_list = ["g+-", "r*-", "b.-", "yo-"]

? ? # 依次畫圖

? ? for num in range(4):

? ? ? ? # 生成測(cè)試數(shù)據(jù)

? ? ? ? x = np.linspace(0.0, 2+num, num=10*(num+1))

? ? ? ? y = np.sin((5-num) * np.pi * x)

? ? ? ? # 子圖的生成方式

? ? ? ? plt.subplot(2, 2, num+1)

? ? ? ? plt.title("子圖 %d" % (num+1))

? ? ? ? plt.plot(x, y, style_list[num])

? ? # 圖形顯示

? ? plt.show()

? ? return

subplot_plot()


4、柱狀圖繪制

def bar_plot():

? ? """

? ? bar plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? means_men = (20, 35, 30, 35, 27)

? ? means_women = (25, 32, 34, 20, 25)

? ? # 設(shè)置標(biāo)題

? ? plt.title("柱狀圖")

? ? # 設(shè)置相關(guān)參數(shù)

? ? index = np.arange(len(means_men))

? ? bar_width = 0.35

? ? # 畫柱狀圖

? ? plt.bar(index, means_men, width=bar_width, alpha=0.2, color="b", label="男生")

? ? plt.bar(index+bar_width, means_women, width=bar_width, alpha=0.8, color="r", label="女生")

? ? plt.legend(loc="upper right", shadow=True)

? ? # 設(shè)置柱狀圖標(biāo)示

? ? for x, y in zip(index, means_men):

? ? ? ? plt.text(x, y+0.3, y, ha="center", va="bottom")

? ? for x, y in zip(index, means_women):

? ? ? ? plt.text(x+bar_width, y+0.3, y, ha="center", va="bottom")

? ? # 設(shè)置刻度范圍/坐標(biāo)軸名稱等

? ? plt.ylim(0, 45)

? ? plt.xlabel("分組Group")

? ? plt.ylabel("得分Scores")

? ? plt.xticks(index+(bar_width/2), ("A組", "B組", "C組", "D組", "E組"))

? ? # 圖形顯示

? ? plt.show()

? ? return

bar_plot()


5、水平柱狀圖

def barh_plot():

? ? """

? ? barh plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? means_men = (20, 35, 30, 35, 27)

? ? means_women = (25, 32, 34, 20, 25)

? ? # 設(shè)置標(biāo)題

? ? plt.title("橫向柱狀圖")

? ? # 設(shè)置相關(guān)參數(shù)

? ? index = np.arange(len(means_men))

? ? bar_height = 0.35

? ? # 畫柱狀圖(水平方向)

? ? plt.barh(index, means_men, height=bar_height, alpha=0.2, color="b", label="Men")

? ? plt.barh(index+bar_height, means_women, height=bar_height, alpha=0.8, color="r", label="Women")

? ? plt.legend(loc="upper right", shadow=True)

? ? # 設(shè)置柱狀圖標(biāo)示

? ? for x, y in zip(index, means_men):

? ? ? ? plt.text(y+0.3, x, y, ha="left", va="center")

? ? for x, y in zip(index, means_women):

? ? ? ? plt.text(y+0.3, x+bar_height, y, ha="left", va="center")

? ? # 設(shè)置刻度范圍/坐標(biāo)軸名稱等

? ? plt.xlim(0, 45)

? ? plt.xlabel("Scores")

? ? plt.ylabel("Group")

? ? plt.yticks(index+(bar_height/2), ("A", "B", "C", "D", "E"))

? ? # 圖形顯示

? ? plt.show()

? ? return

barh_plot()


6磷支、高級(jí)柱狀圖

def bar_advanced_plot():

? ? """

? ? bar advanced plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? means_men = np.array((20, 35, 30, 35, 27, 25, 32, 34, 20, 25))

? ? means_women = np.array((25, 32, 34, 20, 25, 20, 35, 30, 35, 27))

? ? # 設(shè)置標(biāo)題

? ? plt.title("高級(jí)柱狀圖")

? ? # 設(shè)置相關(guān)參數(shù)

? ? index = np.arange(len(means_men))

? ? bar_width = 0.8

? ? # 畫柱狀圖(兩種:X軸以上/X軸以下)

? ? plt.bar(index, means_men, width=bar_width, alpha=0.4, color="b", label="Men")

? ? plt.bar(index, -means_women, width=bar_width, alpha=0.4, color="r", label="Women")

? ? # 畫折線圖(兩種,和柱狀圖對(duì)應(yīng))

? ? plt.plot(index, means_men, marker="o", linestyle="-", color="r", label="Men line")

? ? plt.plot(index, -means_women, marker=".", linestyle="--", color="b", label="Women line")

? ? # 設(shè)置圖形標(biāo)示(兩種,和柱狀圖對(duì)應(yīng))

? ? for x, y in zip(index, means_men):

? ? ? ? plt.text(x, y+1, y, ha="center", va="bottom")

? ? for x, y in zip(index, means_women):

? ? ? ? plt.text(x, -y-1, y, ha="center", va="top")

? ? # 設(shè)置Y軸和圖例位置

? ? plt.ylim(-45, 80)

? ? plt.legend(loc="upper left", shadow=True)

? ? # 圖形顯示

? ? plt.show()

? ? return

bar_advanced_plot()


7棺棵、類表格圖形

def table_plot():

? ? """

? ? table plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? data = np.array([

? ? ? ? [1, 4, 2, 5, 2],

? ? ? ? [2, 1, 1, 3, 6],

? ? ? ? [5, 3, 6, 4, 1]

? ? ])

? ? # 設(shè)置標(biāo)題

? ? plt.title("層次柱狀圖")

? ? # 設(shè)置相關(guān)參數(shù)

? ? index = np.arange(len(data[0]))

? ? color_index = ["r", "g", "b"]

? ? # 聲明底部位置

? ? bottom = np.array([0, 0, 0, 0, 0])

? ? # 依次畫圖,并更新底部位置

? ? for i in range(len(data)):

? ? ? ? plt.bar(index, data[i], width=0.5, color=color_index[i], bottom=bottom, alpha=0.7, label="標(biāo)簽 %d" % i)

? ? ? ? bottom += data[i]

? ? # 設(shè)置圖例位置

? ? plt.legend(loc="upper left", shadow=True)

? ? # 圖形顯示

? ? plt.show()

? ? return

table_plot()


8楼咳、直方圖

def histograms_plot():

? ? """

? ? histograms plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? mu, sigma = 100, 15

? ? x = mu + sigma * np.random.randn(10000)

? ? # 設(shè)置標(biāo)題

? ? plt.title("直方圖")

? ? # 畫直方圖, 并返回相關(guān)結(jié)果

? ? n, bins, patches = plt.hist(x, bins=50, density=1, cumulative=False, color="green", alpha=0.6, label="直方圖")

? ? # 根據(jù)直方圖返回的結(jié)果, 畫折線圖

? ? y = mlab.normpdf(bins, mu, sigma)

? ? plt.plot(bins, y, "r--", label="線條")

? ? # 設(shè)置圖例位置

? ? plt.legend(loc="upper left", shadow=True)

? ? # 圖形顯示

? ? plt.show()

? ? return

histograms_plot()


9、餅狀圖

def pie_plot():

? ? """

? ? pie plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? sizes = [15, 30, 45, 10]

? ? labels = ["Frogs", "中文", "Dogs", "Logs"]

? ? colors = ["yellowgreen", "gold", "lightskyblue", "lightcoral"]

? ? # 設(shè)置標(biāo)題

? ? plt.title("餅圖")

? ? # 設(shè)置突出參數(shù)

? ? explode = [0, 0.05, 0, 0]

? ? # 畫餅狀圖

? ? patches, l_text, p_text = plt.pie(sizes, explode=explode, labels=labels, colors=colors,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? autopct="%1.1f%%", shadow=True, startangle=90)

? ? plt.axis("equal")

? ? # 圖形顯示

? ? plt.show()

? ? return

pie_plot()


10烛恤、散點(diǎn)圖

def scatter_plot():

? ? """

? ? scatter plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? point_count = 1000

? ? x_index = np.random.random(point_count)

? ? y_index = np.random.random(point_count)

? ? # 設(shè)置標(biāo)題

? ? plt.title("散點(diǎn)圖")

? ? # 設(shè)置相關(guān)參數(shù)

? ? color_list = np.random.random(point_count)

? ? scale_list = np.random.random(point_count) * 100

? ? # 畫散點(diǎn)圖

? ? plt.scatter(x_index, y_index, s=scale_list, c=color_list, marker="o")

? ? # 圖形顯示

? ? plt.show()

? ? return

scatter_plot()


11母怜、雷達(dá)圖

def radar_plot():

? ? """

? ? radar plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? labels = np.array(["A組", "B組", "C組", "D組", "E組", "F組"])

? ? data = np.array([68, 83, 90, 77, 89, 73])

? ? theta = np.linspace(0, 2*np.pi, len(data), endpoint=False)

? ? # 數(shù)據(jù)預(yù)處理

? ? data = np.concatenate((data, [data[0]]))

? ? theta = np.concatenate((theta, [theta[0]]))

? ? # 畫圖方式

? ? plt.subplot(111, polar=True)

? ? plt.title("雷達(dá)圖")

? ? # 設(shè)置"theta grid"/"radar grid"

? ? plt.thetagrids(theta*(180/np.pi), labels=labels)

? ? plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)

? ? plt.ylim(0, 100)

? ? # 畫雷達(dá)圖,并填充雷達(dá)圖內(nèi)部區(qū)域

? ? plt.plot(theta, data, "bo-", linewidth=2)

? ? plt.fill(theta, data, color="red", alpha=0.25)

? ? # 圖形顯示

? ? plt.show()

? ? return

radar_plot()


12、三維散點(diǎn)圖

def three_dimension_scatter():

? ? """

? ? 3d scatter plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? x = np.random.random(100)

? ? y = np.random.random(100)

? ? z = np.random.random(100)

? ? color = np.random.random(100)

? ? scale = np.random.random(100) * 100

? ? # 生成畫布(兩種形式)

? ? fig = plt.figure()

? ? fig.suptitle("三維散點(diǎn)圖")

? ? # ax = fig.gca(projection="3d")

? ? ax = fig.add_subplot(111, projection="3d")

? ? # 畫三維散點(diǎn)圖

? ? ax.scatter(x, y, z, s=scale, c=color, marker=".")

? ? # 設(shè)置坐標(biāo)軸圖標(biāo)

? ? ax.set_xlabel("X Label")

? ? ax.set_ylabel("Y Label")


? ? ax.set_zlabel("Z Label")

? ? # 設(shè)置坐標(biāo)軸范圍

? ? ax.set_xlim(0, 1)

? ? ax.set_ylim(0, 1)

? ? ax.set_zlim(0, 1)

? ? # 圖形顯示

? ? plt.show()

? ? return

three_dimension_scatter()


13缚柏、三維折線圖

def three_dimension_line():

? ? """

? ? 3d line plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? x = np.linspace(0, 1, 1000)

? ? y = np.linspace(0, 1, 1000)

? ? z = np.sin(x * 2 * np.pi) / (y + 0.1)

? ? # 生成畫布(兩種形式)

? ? fig = plt.figure()

? ? ax = fig.gca(projection="3d", title="三維折線圖")

? ? # ax = fig.add_subplot(111, projection="3d", title="plot title")

? ? # 畫三維折線圖

? ? ax.plot(x, y, z, color="red", linestyle="-")

? ? # 設(shè)置坐標(biāo)軸圖標(biāo)

? ? ax.set_xlabel("X Label")

? ? ax.set_ylabel("Y Label")

? ? ax.set_zlabel("Z Label")

? ? # 圖形顯示

? ? plt.show()

? ? return

three_dimension_line()

14苹熏、三維柱狀圖

def three_dimension_bar():

? ? """

? ? 3d bar plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)(位置數(shù)據(jù))

? ? xpos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

? ? ypos = [2, 3, 4, 5, 1, 6, 2, 1, 7, 2]

? ? zpos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

? ? # 生成測(cè)試數(shù)據(jù)(柱形參數(shù))

? ? dx = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

? ? dy = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

? ? dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

? ? # 生成畫布(兩種形式)

? ? fig = plt.figure()

? ? ax = fig.gca(projection="3d", title="三維柱狀圖")

? ? # 畫三維柱狀圖

? ? ax.bar3d(xpos, ypos, zpos, dx, dy, dz, alpha=0.5)

? ? # 設(shè)置坐標(biāo)軸圖標(biāo)

? ? ax.set_xlabel("X Label")

? ? ax.set_ylabel("Y Label")

? ? ax.set_zlabel("Z Label")

? ? # 圖形顯示

? ? plt.show()

? ? return

three_dimension_bar()

15、圖形填充

def fill_plot():

? ? """

? ? fill plot

? ? """

? ? # 生成測(cè)試數(shù)據(jù)

? ? x = np.linspace(-2*np.pi, 2*np.pi, 1000, endpoint=True)

? ? y = np.sin(x)

? ? # 設(shè)置標(biāo)題

? ? plt.title("填充圖")

? ? # 畫圖

? ? plt.plot(x, y, color="blue", alpha=1.00)

? ? # 填充圖形, plt.fill_between(x, y1, y2, where=None, *kwargs)

? ? plt.fill_between(x, 0, y, where=(y > 0), color="blue", alpha=0.25)

? ? plt.fill_between(x, 0, y, where=(y < 0), color="red", alpha=0.25)

? ? # 圖形顯示

? ? plt.show()

? ? return

fill_plot()

參考鏈接:https://zhuanlan.zhihu.com/p/22952801

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末币喧,一起剝皮案震驚了整個(gè)濱河市轨域,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌杀餐,老刑警劉巖干发,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異史翘,居然都是意外死亡枉长,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門琼讽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來必峰,“玉大人,你說我怎么就攤上這事钻蹬『鹨希” “怎么了?”我有些...
    開封第一講書人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵脉让,是天一觀的道長桂敛。 經(jīng)常有香客問我功炮,道長,這世上最難降的妖魔是什么术唬? 我笑而不...
    開封第一講書人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任薪伏,我火速辦了婚禮,結(jié)果婚禮上粗仓,老公的妹妹穿的比我還像新娘嫁怀。我一直安慰自己,他們只是感情好借浊,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開白布塘淑。 她就那樣靜靜地躺著,像睡著了一般蚂斤。 火紅的嫁衣襯著肌膚如雪存捺。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,929評(píng)論 1 290
  • 那天曙蒸,我揣著相機(jī)與錄音捌治,去河邊找鬼。 笑死纽窟,一個(gè)胖子當(dāng)著我的面吹牛肖油,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播臂港,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼森枪,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了审孽?” 一聲冷哼從身側(cè)響起县袱,我...
    開封第一講書人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎瓷胧,沒想到半個(gè)月后显拳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡搓萧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年杂数,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瘸洛。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡揍移,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出反肋,到底是詐尸還是另有隱情那伐,我是刑警寧澤,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站罕邀,受9級(jí)特大地震影響畅形,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜诉探,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一日熬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧肾胯,春花似錦竖席、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至艳馒,卻和暖如春憎亚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背鹰溜。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來泰國打工虽填, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人曹动。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓,卻偏偏與公主長得像牲览,于是被迫代替她去往敵國和親墓陈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350