Matplotlib 图表坐标轴显示问题

正在学习wizardforcel的专栏的:

Python 数据科学入门教程:Matplotlib( 点击打开链接)

其中 第五章 堆叠图 使用 下面源码绘制图形时候出现如下 图表区偏离 Y轴的问题,非常难看。

import matplotlib.pyplot as plt

days = [1,2,3,4,5]

sleeping = [7,8,6,11,7]
eating =   [2,3,4,3,2]
working =  [7,8,7,2,2]
playing =  [8,5,7,8,13]


plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)

plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()


Matplotlib 图表坐标轴显示问题_第1张图片


百度找到了解决方法:设置x,y 坐标范围,

import matplotlib.pyplot as plt
# 下面两行代码专门用来解决中文显示问题
from pylab import *  
mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']  

days = [1,2,3,4,5]

sleeping = [7,8,6,11,7]
eating =   [2,3,4,3,2]
working =  [7,8,7,2,2]
playing =  [8,5,7,8,13]

# 绘制标签图例
plt.plot([],[],color='m', label='Sleeping-睡觉', linewidth=5)
plt.plot([],[],color='c', label='Eating-吃饭', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)

plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])

# 设置x,y轴的取值范围为:
plt.ylim(0, 24)
plt.xlim(1, 5)

plt.xlabel('x-date')
plt.ylabel('y-item')
plt.title('Interesting Graph\nCheck it out')
# 绘制标签图例
plt.legend()
plt.show()

Matplotlib 图表坐标轴显示问题_第2张图片


完美解决!



你可能感兴趣的:(Python,编程基础)