2

我已经编写了下面的代码来可视化一个joyplot。尝试使用 更改 x 轴标签axes.set_xticks时,出现错误:AttributeError: 'list' object has no attribute 'set_xticks'

import joypy
import pandas as pd
from matplotlib import pyplot as plt

data = pd.DataFrame.from_records([['twitter', 1],
 ['twitter', 6],
 ['wikipedia', 1],
 ['wikipedia', 3],
 ['indymedia', 1],
 ['indymedia', 9]], columns=['platform','day'])

# Get number of days in the dataset
numdays = max(set(data['day'].tolist()))

# Generate date strings from a manually set start date
start_date = "2010-01-01"
dates = pd.date_range(start_date, periods=numdays)
dates = [str(date)[:-9] for date in dates]

fig, axes = joypy.joyplot(data,by="platform")
axes.set_xticks(range(numdays)); axes.set_xticklabels(dates)

plt.show()

预期的输出应如下所示,但日期dates为刻度标签。

在此处输入图像描述

4

2 回答 2

2

由于joypy.joyplot(..)返回 , 的元组figureaxes并且axes应该是轴列表,因此您可能希望为最后一个轴设置标签,

axes[-1].set_xticks(range(numdays))
axes[-1].set_xticklabels(dates)
于 2017-11-18T14:31:02.997 回答
0

要使用 python matplotlib 制作日期图,您应该使用 plot_date 函数。

无花果,ax = plt.subplots()
ax.plot_date(dates, data1, '-')

我把完整的例子放在pastebin中,点击链接: https ://pastebin.com/sVPUZaeM

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from random import randrange, random
from datetime import datetime

#generate date list
start_date = np.datetime64('2010-01-01').astype(datetime)
numdays = 10
dates = pd.date_range(start_date, periods=numdays)

#Generate data example
data1 = [(random()+idx)**1.2 for idx in range(len(dates))]
data2 = [(random()+idx)**1.5 for idx in range(len(dates))]

#plot
fig, ax = plt.subplots()
ax.plot_date(dates, data1, '-')
ax.plot_date(dates, data2, '-')

#set the label for x and y and title
plt.title('Matplot lib dates wc example')
plt.xlabel('Dates')
plt.ylabel('Random values example')

#date format
ax.fmt_xdata = DateFormatter('%Y%m%d')
ax.grid(True)
fig.autofmt_xdate()

plt.show()

Python 版本测试成功:2.7.12
此代码生成:this follow plot

于 2017-11-18T15:41:39.163 回答