1. 程式人生 > >Python畫圖基本方法總結

Python畫圖基本方法總結

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是每個刻度開始的位置