關于Matplotlib中文顯示的問題

python中的matplotlib僅支持Unicode編碼,默認是不顯示中文的,如果把字符串是中文,在顯示的時候所以的文字都變成了框框,要解決這個問題需要設置一下文字的字體,有下面2種方法:

第一種方法:在代碼中動態設置 這種方式不需要修改配置文件,比較方便,但只適用于加上去的文字,下面是具體步驟:

1.首先要再python腳本中的開頭加上后面的內容:#-- coding: utf-8 --,即用utf8編碼

2.然后在代碼中動態設置字體

#這里是主要的幾行代碼
#-- coding: utf-8 --
......
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc", size=14)  
plt.xlabel(u'職位需求(位)')
......
# 如果你在作圖過程中遇到下面這種情況,那么第一種方法就不再適用了
1.png
第二種方法:Matplotlib中文顯示有問題,當然可以修改配置文件matplotlibrc ,一勞永逸,推薦使用這種方法,下面是具體步驟:

1、在python的安裝目錄中找到配置文件matplotlibrc
我用的是Anaconda里的python,所以我的是在F:\Anaconda3\Lib\site-packages\matplotlib\mpl-data\matplotlibrc,用任意文本編輯器打開。

2、找到141行的font.family : sans-serif
將其前面的#注釋號去掉

3、找到152行的font.sans-serif : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
將【AR PL UMing CN, SimHei】添加在最前面,其中AR PL UMing CN和SimHei分別代表宋體和黑體,并將前面的#注釋號去掉

4、更改267行的axes.unicode_minus :True
將True改為False

實戰

爬取前程無憂上【上海】【本科】【實習】【無工作經驗】關于【統計】的職業需求,關于對于編碼的信息可以從js里拿到

import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
import csv
import json
from requests.exceptions import RequestException

url1='http://m.51job.com/ajax/search/joblist.ajax.php?'
url2 = 'http://m.51job.com/search/joblist.php?'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'}

def get_page_index(i,url):
    data = {
        'keyword':'統計',   
        'jobarea':'020000',   #地區編碼
        'jobterm': '03',   #工作類型編碼
        'workyear': '01',   #工作經驗編碼
        'degree': '04',   #學歷要求編碼
        'pageno':str(i)
    }   
    try:
        response = requests.get(url,params=data,headers=headers)
        if response.status_code == 200:
            #print(response.text)
            return response.text
        return None
    except RequestException:
        print('請求索引頁出錯')
        return None

def the_sum():   #獲取總職位需求數
    html=get_page_index(1,url2)
    soup=BeautifulSoup(html,'lxml')
    sum=soup.find(class_='result').span.text
    sum=int(sum)
    show = '總計職位%d個' % sum
    print(show)
    t=int(sum/30)
    return t

def parse_the_index(i):
    html=get_page_index(i,url1)
    #print(html)
    js=json.loads(html)
    items=(js.get('data'))
    #print(items)
    return items

def plt_out():   #畫圖
    f = pd.read_csv(r'tj03.csv')
    jabore_count = f.jobareaname.value_counts()
    #print(jabore_count)
    frame = pd.DataFrame(jabore_count)
    print(frame)
    frame.plot(kind='barh')
    plt.xlabel(u'職位需求(位)')
    plt.show()

def main():
    with open('tj03.csv', 'a', encoding='utf-8') as csvfile:
        fieldnames = ['jobareaname','cjobname', 'jobsalaryname', 'cocname']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        sum=the_sum()
        for i in range(1,sum+1):
            get_page_index(i,url1)
            items=parse_the_index(i)
            for item in items:
                del item['isexpired']
                del item['coid']
                del item['jobid']
                del item['isjump']
                del item['jumpurl']
                del item['hasposted']
                print(item)
                writer.writerow(item)
    plt_out()

if __name__ == '__main__':
    main()

最后得到csv文件和柱狀圖


2.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容