pandas 条形图中的刻度标签重叠 [英] Tick labels overlap in pandas bar chart

查看:37
本文介绍了 pandas 条形图中的刻度标签重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR:在大熊猫中,如何绘制条形图,使其x轴刻度线标签看起来像折线图的标签?

TL;DR: In pandas how do I plot a bar chart so that its x axis tick labels look like those of a line chart?

我制作了一个间隔均匀的时间序列(每天一个项目),并且可以将其绘制得很好:

I made a time series with evenly spaced intervals (one item each day) and can plot it like such just fine:

intensity[350:450].plot()
plt.show()

但是切换到条形图造成了这个混乱:

But switching to a bar chart created this mess:

intensity[350:450].plot(kind = 'bar')
plt.show()

然后我直接使用 matplotlib 创建了一个条形图,但它缺少 Pandas 的漂亮日期时间序列刻度标签格式化程序:

I then created a bar chart using matplotlib directly but it lacks the nice date time series tick label formatter of pandas:

def bar_chart(series):
    fig, ax = plt.subplots(1)
    ax.bar(series.index, series)
    fig.autofmt_xdate()
    plt.show()

bar_chart(intensity[350:450])

这是强度系列的摘录:

intensity[390:400]

2017-03-07    3
2017-03-08    0
2017-03-09    3
2017-03-10    0
2017-03-11    0
2017-03-12    0
2017-03-13    2
2017-03-14    0
2017-03-15    3
2017-03-16    0
Freq: D, dtype: int64 

我可以全力以赴,完全手动创建刻度标签,但我不想让matplotlib婴儿,让熊猫来做它的工作,并做它在第一个图中所做的事情,但是要用条形图.那我该怎么做?

I could go all out on this and just create the tick labels by hand completely but I'd rather not have to baby matplotlib and let do pandas its job and do what it did in the very first figure but with a bar plot. So how do I do that?

推荐答案

熊猫柱状图是分类图.他们为每个类别创建一个勾号(+标签).如果类别是日期,并且那些日期是连续的,则可以将某些日期排除在外,例如仅绘制出第五个类别,

Pandas bar plots are categorical plots. They create one tick (+label) for each category. If the categories are dates and those dates are continuous one may aim at leaving certain dates out, e.g. to plot only every fifth category,

ax = series.plot(kind="bar")
ax.set_xticklabels([t if not i%5 else "" for i,t in enumerate(ax.get_xticklabels())])

相反,matplotlib条形图是数字图.在这里可以应用一个有用的行情自动收录器,它对每周,每月或任何需要的日期进行记时.

In contrast, matplotlib bar charts are numberical plots. Here a useful ticker can be applied, which ticks the dates weekly, monthly or whatever is needed.

此外,matplotlib可以完全控制刻度线位置及其标签.

In addition, matplotlib allows to have full control over the tick positions and their labels.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates

index = pd.date_range("2018-01-26", "2018-05-05")
series = pd.Series(np.random.rayleigh(size=100), index=index)

plt.bar(series.index, series.values)
plt.gca().xaxis.set_major_locator(dates.MonthLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter("%b\n%Y"))
plt.show()

这篇关于 pandas 条形图中的刻度标签重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆