Python畫圖基本方法總結__Python

來源:互聯網
上載者:User
import pandas as pd

import numpy as np


frommatplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib as mpl
# matplotlib.use('Agg')
import matplotlib.pyplot as plt  


1.設定畫布大小

   plt.figure(figsize=(19, 12))    #設定畫布尺寸大小,會影響自動彈出來圖框的大小
    ax = plt.subplot(1, 1, 1)           # 畫子圖

2. 取不同顏色個數
    col_num = df.shape[1]
    colormap = plt.cm.gist_ncar   # 顏色軸連續的,python內建的字母顏色只有7中,有時不夠用

    colors = [colormap(i) for i in np.linspace(0, 0.9, col_num)]

3.畫點圖,折線圖,label會對應legend
    for i in range(1, df.shape[1]):
        plt.plot(df.iloc[:, 0], df_total_guodu_3_relative30up.iloc[:, i], color=colors[i],
                 linestyle='-', linewidth=6, label='%s' % df.columns[i])

4.顯示中文時指定路徑

  用fc-list : lang=zh在終端裡查詢包含哪些字型

    myfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/ukai.ttc')   #指定中文字型路徑
    myfont1 = mpl.font_manager.FontProperties(fname='/usr/share/fonts/opentype/noto/NotoSansCJK.ttc',size=20)

   ax.legend(legend, loc='best', bbox_to_anchor=(1.03, -0.04),ncol=8, frameon=False,prop=myfont1) 

   # 不能單獨設定字型大小,fontsize,prop不能同時用,如果只顯示英文數字,不需要指定字型,則可直接用fontsize

5.設定標籤是橫向擺放,定義函數flip

 ----------------------------------------------------------------------------------------------------------  

import itertools

 def flip(items, ncol):
     return itertools.chain(*[items[i::ncol] for i in range(ncol)])

-------------------------------------------------------------------------------------------------------

   handles, labels = ax.get_legend_handles_labels()   
    plt.legend(flip(handles, 8), flip(labels, 8), loc='best', fontsize=17, bbox_to_anchor=(0.9, -0.02), ncol=8,
               frameon=False)

6.標題
    plt.title(u'過渡', fontproperties=myfont, fontsize=25)

7.軸的各種設定
    xmajorLocator = MultipleLocator(1)                     # 將x主刻度標籤設定為1的倍數
    ax.xaxis.set_major_locator(xmajorLocator)

    ymajorFormatter = FormatStrFormatter('%.2f')     # 設定y軸標籤文本的格式兩位小數(‘%.2f%%’)百分比符號格式
    ax.yaxis.set_major_formatter(ymajorFormatter)


  ticklab = ax.yaxis.get_ticklabels()[0]                          #設定y軸標籤的位置
  trans = ticklab.get_transform()
  ax.yaxis.set_label_coords(-0.06, 6000, transform=trans)


    ax.set_ylim([0, 5])  #設定y軸取值範圍
    ax.set_xlim([0, 11])  # 設定x軸取值範圍

    for tick in ax.xaxis.get_major_ticks():  # 設定x軸刻度文本的大小
        tick.label1.set_fontsize(18)

    for tick in ax.yaxis.get_major_ticks():  # 設定y軸刻度文本的大小
        tick.label1.set_fontsize(18)

    ax.yaxis.grid(True)  # y座標軸的網格

8.儲存圖片

    plt.savefig('./total.jpg', format='jpg') # 儲存圖片


9.累計柱狀圖

# 每個比例直條圖的個數,方便後面畫個數
N = df[1]-1
left = np.arange(N)
width = 0.55

height = []

height.append(df[0, 1:3]/1000000)
plt.bar(left, height[0], width,  facecolor = colors[0], edgecolor = 'white', align='center')

for i in range(1, df[0]):
    height.append(df_total_owing.iloc[i, 1:3]/1000000)
    plt.bar(left, height


10. 設定橫軸標籤是其中文,日期,並旋轉角度

N = df.shape[0]                       #設定x軸刻度標籤
left = np.arange(N)
x_ticks = df.iloc[:, 0]          # 設定x軸的刻度值並旋轉,文本刻度值太長,放在後面不管用
plt.xticks(left, x_ticks, rotation=90)          # left是每個刻度開始的位置



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.