赞
踩
最近在用matplotlib画图时遇到了画子图,上边子图不显示xticks的问题,如下图:
代码:
- # matplotlib -- version 3.2.2
- import numpy as np
- import matplotlib.pyplot as mp
-
- names = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"]
- data1 = np.array([2, 4, 6, 8, 10, 12])
- data2 = np.array([2, 6, 5, 3, 7, 6])
- xs = np.arange(len(names))
-
- mp.figure("Test subplot", facecolor="lightgray")
- mp.subplot(211)
- mp.bar(xs, data1, color="dodgerblue", label="Data1")
- mp.xticks(xs, names)
- mp.gcf().autofmt_xdate()
- mp.legend()
-
- mp.subplot(212)
- mp.bar(xs, data2, color="orangered", label="Data2")
- mp.xticks(xs, names)
- mp.gcf().autofmt_xdate()
- mp.legend()
-
- mp.show()
最终,找到的问题的原因在于xticks使用了自动旋转一定角度: mp.gcf().autofmt_xdate()
将其注释掉即可,附上修改后的代码和图片:
- # matplotlib -- version 3.2.2
- import numpy as np
- import matplotlib.pyplot as mp
-
- names = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"]
- data1 = np.array([2, 4, 6, 8, 10, 12])
- data2 = np.array([2, 6, 5, 3, 7, 6])
- xs = np.arange(len(names))
-
- mp.figure("Test subplot", facecolor="lightgray")
- mp.subplot(211)
- mp.bar(xs, data1, color="dodgerblue", label="Data1")
- mp.xticks(xs, names)
- # mp.gcf().autofmt_xdate()
- mp.legend()
-
- mp.subplot(212)
- mp.bar(xs, data2, color="orangered", label="Data2")
- mp.xticks(xs, names)
- # mp.gcf().autofmt_xdate()
- mp.legend()
-
- mp.show()
如果还是想着将xticks的显示旋转一定角度,可使用 mp.xticks(xs, names, rotation=30) 替换 mp.gcf().autofmt_xdate() 即可,其中rotation的代表旋转的角度,大小可自行调整。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。