2017-10-13 28 views
-1

我有以下数据框:如何有两个Y尺度在matplotlib同时对x轴的日期

date  us_dollar active_user_count 
    2016-01-01 4.76  1083 
    2016-01-02 46.78  1558 
    2016-01-03 60.47  1872 
    2016-01-04 218.72  1884 
    2016-01-05 78.90  2068 

需要想象他们在我的情节将有两个不同的Y标尺为每列的方式我采取以下方法:

ax=date_usdollar_user[['date','us_dollar']].set_index('date').plot(figsize=(30, 20) ,linewidth=5);plt.xticks(rotation='vertical') 
ax2 = ax.twinx() 
ax2.plot(ax.get_xticks(),date_usdollar_user[['date','active_user_count']].set_index('date'),marker='o',linewidth=5) 
ax.tick_params(labelsize=20) 
ax2.tick_params(labelsize=20) 

plt.grid(True) 
plt.show() 

,但我收到以下错误:

x and y must have same first dimension, but have shapes (13,) and (366, 1) 

回答

0

不前夕您的情节中的数据点有其自己的标记。这里有13个标签,但有366个数据点,因此是错误的。

如果你有一个数据帧df有三列xyz,您可以通过

ax=df[['x','y']].set_index('x').plot() 
ax2 = ax.twinx() 
df[['x','z']].set_index('x').plot(ax=ax2) 
0

绘制它两张轴如果你通常要绘制两列不同的轴,那么你也可以做以下情况:

import matplotlib as mpl 
rc_fonts = {"text.usetex": True, "font.size": 30, 'mathtext.default': 'regular', 'axes.titlesize': 33, "axes.labelsize": 33, "legend.fontsize": 30, "xtick.labelsize": 30, "ytick.labelsize": 30, 'figure.titlesize': 33, 'figure.figsize': (15, 9.3), 'text.latex.preamble': [ 
    r'\usepackage{amsmath,amssymb,bm,physics,lmodern}'], "font.family": "serif", "font.serif": "computer modern roman", } 
mpl.rcParams.update(rc_fonts) 
import matplotlib.pylab as plt 
import matplotlib.dates as mdates 
import pandas as pd 

df = pd.DataFrame(zip(range(10), range(10)[::-1], [pd.datetime(year=2017, month=1, day=i) for i in range(1,11)]), columns=['y1', 'y2', 'date']) 

plt.clf() 
fig = plt.gcf() 
ax1 = fig.add_subplot(111) 
ax1.plot(df['date'], df['y1'], 'ko:', label='$y_1$') 
ax1.set_xlabel('Date', labelpad=5) 
ax1.set_ylabel('$y_1$') 
ax1.set_title('Two $y$-axes', y=1.02) 
ax1.legend(loc=(0.1, 0.5), handlelength=3, handletextpad=0.1, frameon=False, numpoints=1) 
ax2 = ax1.twinx() 
ax2.plot(df['date'], df['y2'], 'r^--', label='$y_2$') 
ax2.set_ylabel('$y_2$') 
ax2.legend(loc=(0.1, 0.4), handlelength=3, handletextpad=0.1, frameon=False, numpoints=1) 
plt.gca().xaxis.set_minor_locator(mdates.DayLocator()) 
plt.gca().xaxis.set_minor_formatter(mdates.DateFormatter('%a\n%d-%m')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('')) 
ax1.xaxis.set_tick_params(which='both', pad=20) 
plt.savefig('example.pdf', format='pdf', bbox_inches='tight') 

其产生:

enter image description here

相关问题