有xticks在Pandas的Seaborn regplot中显示月份

问题描述 投票:0回答:1

我无法想象如何使xticks显示Months。

对于可重现的示例,我的数据是:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

json = '{"index":{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16},"Date":{"0":1516147200000,"1":1516752000000,"2":1517788800000,"3":1520208000000,"4":1520985600000,"5":1522281600000,"6":1522886400000,"7":1523404800000,"8":1523491200000,"9":1524096000000,"10":1525305600000,"11":1525737600000,"12":1526428800000,"13":1527811200000,"14":1533686400000,"15":1534377600000,"16":1534809600000},"FB":{"0":0.978943931,"1":1.0282769543,"2":0.999118052,"3":0.994377665,"4":1.0152684601,"5":0.880773866,"6":0.8782934503,"7":0.91676777,"8":0.9032631287,"9":0.9265792518,"10":0.959210704,"11":0.9862198213,"12":1.0098114818,"13":1.0692867773,"14":1.0207253613,"15":0.962958874,"16":0.9514937543},"month":{"0":1,"1":1,"2":2,"3":3,"4":3,"5":3,"6":4,"7":4,"8":4,"9":4,"10":5,"11":5,"12":5,"13":6,"14":8,"15":8,"16":8}}'

toy_data = pd.read_json(json)

enter image description here

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('Share Price Facebook, Google and the SP500')
sns.regplot( x = 'index', y = 'FB', data = toy_data , label = 'FB', fit_reg = True)

plt.show()

enter image description here

我想修改代码,以便在x轴上出现观察范围的月份。这是刻度标签0和1将被替换为'Jan'(出现一次),刻度标签2将被替换为'Feb',刻度标签3,4,5将被'March'(出现一次)等等。

您的建议将不胜感激。

python-3.x pandas matplotlib label seaborn
1个回答
0
投票

您可以将日期转换为数字,并将这些数字用作xregplot输入。然后,您可以将您的ticklabels格式化为日期。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns

json = '{"index":{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16},"Date":{"0":1516147200000,"1":1516752000000,"2":1517788800000,"3":1520208000000,"4":1520985600000,"5":1522281600000,"6":1522886400000,"7":1523404800000,"8":1523491200000,"9":1524096000000,"10":1525305600000,"11":1525737600000,"12":1526428800000,"13":1527811200000,"14":1533686400000,"15":1534377600000,"16":1534809600000},"FB":{"0":0.978943931,"1":1.0282769543,"2":0.999118052,"3":0.994377665,"4":1.0152684601,"5":0.880773866,"6":0.8782934503,"7":0.91676777,"8":0.9032631287,"9":0.9265792518,"10":0.959210704,"11":0.9862198213,"12":1.0098114818,"13":1.0692867773,"14":1.0207253613,"15":0.962958874,"16":0.9514937543}}'
df = pd.read_json(json)
df["Date2"] = mdates.date2num(pd.to_datetime(df["Date"]))

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('Share Price Facebook, Google and the SP500')
sns.regplot( x = 'Date2', y = 'FB', data = df , label = 'FB', fit_reg = True, ax=ax)

loc = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.