python使用matplotlib繪圖時圖例顯示問題的解決
前言
matplotlib是基于Python語言的開源項目,旨在為Python提供一個數(shù)據(jù)繪圖包。在使用Python matplotlib庫繪制數(shù)據(jù)圖時,需要使用圖例標注數(shù)據(jù)類別,但是傳參時,會出現(xiàn)圖例解釋文字只顯示第一個字符,需要在傳參時在參數(shù)后加一個逗號(應該是python語法,加逗號,才可以把參數(shù)理解為元組類型吧),就可解決這個問題,
示例如下
import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator from pylab import mpl xmajorLocator = MultipleLocator(24 * 3) #將x軸主刻度標簽設置為24 * 3的倍數(shù) ymajorLocator = MultipleLocator(100 * 2) #將y軸主刻度標簽設置為100 * 2的倍數(shù) # 設置中文字體 mpl.rcParams['font.sans-serif'] = ['SimHei'] # 導入文件數(shù)據(jù) data = np.loadtxt('H:/dataset/統(tǒng)計數(shù)據(jù)_每小時_ba.csv', delimiter=',', dtype=int) # 截取數(shù)組數(shù)據(jù) x = data[:, 0] y = data[:, 1] plt.figure(num=1, figsize=(8, 6)) ax = plt.subplot(111) ax.xaxis.set_major_locator(xmajorLocator) ax.yaxis.set_major_locator(ymajorLocator) ax.xaxis.grid(True, which='major') #x坐標軸的網(wǎng)格使用主刻度 ax.yaxis.grid(True, which='major') #x坐標軸的網(wǎng)格使用主刻度 plt.xlabel('時間索引') plt.ylabel('活動頻數(shù)') plt.title('折線圖') plt.xlim(0, 1152) plt.ylim(0, 2200) #plt.plot(x, y, 'rs-') line1 = ax.plot(x, y, 'b.-') ax.legend(line1, ('微博')) plt.show()
顯示效果如下
代碼修改
from pylab import mpl xmajorLocator = MultipleLocator(24 * 3) #將x軸主刻度標簽設置為24 * 3的倍數(shù) ymajorLocator = MultipleLocator(100 * 2) #將y軸主刻度標簽設置為100 * 2的倍數(shù) # 設置中文字體 mpl.rcParams['font.sans-serif'] = ['SimHei'] # 導入文件數(shù)據(jù) data = np.loadtxt('H:/dataset/統(tǒng)計數(shù)據(jù)_每小時_ba.csv', delimiter=',', dtype=int) # 截取數(shù)組數(shù)據(jù) x = data[:, 0] y = data[:, 1] plt.figure(num=1, figsize=(8, 6)) ax = plt.subplot(111) ax.xaxis.set_major_locator(xmajorLocator) ax.yaxis.set_major_locator(ymajorLocator) ax.xaxis.grid(True, which='major') #x坐標軸的網(wǎng)格使用主刻度 ax.yaxis.grid(True, which='major') #x坐標軸的網(wǎng)格使用主刻度 plt.xlabel('時間索引') plt.ylabel('活動頻數(shù)') plt.title('折線圖') plt.xlim(0, 1152) plt.ylim(0, 2200) #plt.plot(x, y, 'rs-') line1 = ax.plot(x, y, 'b.-') ax.legend(line1, ('微博',)) # 多加一個逗號 plt.show()
顯示效果如下
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學習或者使用python能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
python實現(xiàn)UDP協(xié)議下的文件傳輸
這篇文章主要為大家詳細介紹了python實現(xiàn)UDP協(xié)議下的文件傳輸,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-03-03Windows下創(chuàng)建定時任務執(zhí)行Python腳本的方法實現(xiàn)
Python定時任務執(zhí)行,本文主要介紹了Windows下創(chuàng)建定時任務執(zhí)行Python腳本的方法實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-11-11YOLOv5車牌識別實戰(zhàn)教程(六)性能優(yōu)化與部署
這篇文章主要介紹了YOLOv5車牌識別實戰(zhàn)教程(六)性能優(yōu)化與部署,在這個教程中,我們將一步步教你如何使用YOLOv5進行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下2023-04-04Python自動化爬取天眼查數(shù)據(jù)的實現(xiàn)
本文將結(jié)合實例代碼,介紹Python自動化爬取天眼查數(shù)據(jù)的實現(xiàn),對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-06-06python print()函數(shù)的end參數(shù)和sep參數(shù)的用法說明
這篇文章主要介紹了python print()函數(shù)的end參數(shù)和sep參數(shù)的用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05