更改绘图的轴长度,使图表在Python中看起来更好

时间:2016-08-26 22:05:41

标签: python matplotlib plot

我在Python中使用以下代码来绘制四个向量。但是,正如您所看到的那样,由于不同的曲线在某些点上相互粘连并且它们彼此非常接近,因此情节看起来并不好看。如何更改绘图以使曲线更好地分离并且绘图看起来更好?

plt.gca().set_color_cycle(['red', 'green','blue','purple'])
plt.plot(UB_user_util_list)
plt.plot(UB_Greedy_user_util_list)
plt.plot(IB_user_util_list,)
plt.plot(IB_Greedy_user_util_list)
plt.legend(['UB', 'UB_Optimized','IB','IB_opimized'], loc='upper left')
plt.title("User Utility values over time/split data based on time")
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:0)

如何将它们分成四个子图?

enter image description here

你可以像使用matplotlib一样模仿seaborn / ggplot / pandas风格:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.rcParams['axes.linewidth'] = 0.0

vex = (np.random.rand(100),)*4
v_attr = [('r','v1'), ('orange', 'v2'), 
          ('g', 'v3'), ('b', 'v4')]

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', 
                                                   sharey='row')

for s,v,(c,l) in zip([ax1, ax2, ax3, ax4], vex, v_attr):
    s.set_axis_bgcolor('#dddddd')
    s.grid(b=True, which='major', c='white', ls='-', zorder=-1, 
           lw=0.75, alpha=0.64)
    s.set_ylim(0,max(v)*1.35)
    s.tick_params('both', pad=4, labelsize=8, which='major', 
                  direction='out', top='off', right='off')
    s.plot(v, label=l, c=c, zorder=3)
    s.legend(frameon=False, )

或者,您仍然可以进行相同的情节比较,也许您可​​以使用alpha来单独突出显示背景中其他线条的每一行:

enter image description here

import numpy.random as rand

def rand_line():
    return rand.normal(rand.randint(5,12), 
                       rand.ranf()*3, 100)

lines = [rand_line() for _ in range(4)]
labels = [('r','v1'), ('purple','v2'), 
          ('g','v3'), ('b','v4')]

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col',  
                                                   sharey='row')
subplots = [ax1, ax2, ax3, ax4]
for i,s in enumerate(subplots):
    for j,(v,l) in enumerate(zip(lines,labels)):
        a = (.9 if j==i else 0.25)
        s.plot(v, zorder=3, alpha=a, c=l[0], label=l[1])
    s.legend(loc='lower center', ncol=4, fontsize=10)

fig.tight_layout()
plt.savefig('line_subplots-highlight.png')