python使用matplotlib绘图时图例显示问题的解决

yipeiwu_com7年前Python基础

前言

matplotlib是基于Python语言的开源项目,旨在为Python提供一个数据绘图包。在使用Python matplotlib库绘制数据图时,需要使用图例标注数据类别,但是传参时,会出现图例解释文字只显示第一个字符,需要在传参时在参数后加一个逗号(应该是python语法,加逗号,才可以把参数理解为元组类型吧),就可解决这个问题,

示例如下

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的倍数 
ymajorLocator = MultipleLocator(100 * 2) #将y轴主刻度标签设置为100 * 2的倍数 
 
# 设置中文字体 
mpl.rcParams['font.sans-serif'] = ['SimHei'] 
 
# 导入文件数据 
data = np.loadtxt('H:/dataset/爸爸去哪儿/统计数据_每小时_ba.csv', delimiter=',', dtype=int) 
 
# 截取数组数据 
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坐标轴的网格使用主刻度 
ax.yaxis.grid(True, which='major') #x坐标轴的网格使用主刻度 
 
plt.xlabel('时间索引') 
plt.ylabel('活动频数') 
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的倍数 
ymajorLocator = MultipleLocator(100 * 2) #将y轴主刻度标签设置为100 * 2的倍数 
 
# 设置中文字体 
mpl.rcParams['font.sans-serif'] = ['SimHei'] 
 
# 导入文件数据 
data = np.loadtxt('H:/dataset/爸爸去哪儿/统计数据_每小时_ba.csv', delimiter=',', dtype=int) 
 
# 截取数组数据 
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坐标轴的网格使用主刻度 
ax.yaxis.grid(True, which='major') #x坐标轴的网格使用主刻度 
 
plt.xlabel('时间索引') 
plt.ylabel('活动频数') 
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() 

显示效果如下

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python 实现目录复制的三种小结

复制目录: 包含多层子目录 方法: 递归, 深度遍历,广度遍历 深度遍历&广度遍历: 思路: 1.获得源目录子级目录,并设置目标目录的子级路径 1.1在此就创建两个栈(或者队列),将原目...

使用python3实现操作串口详解

通过引用serial模块包,来操作串口。 1、查看串口名称 在Linux和Windows中,串口的名字规则不太一样。 需要事先查看。 Linux下的查看串口命令 root@D2:...

Django在Win7下的安装及创建项目hello word简明教程

python广受欢迎的编程语言之一,本文简述了python 的django 框架安装与开发。 Django在Win7下的安装及创建项目hello word,相对而言非常简单,这里直接给出...

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...

Python简单读取json文件功能示例

本文实例讲述了Python简单读取json文件功能。分享给大家供大家参考,具体如下: read_json.json: { "rule":{ "namespace":"st...