python绘图设置x轴年份
时间: 2023-07-07 13:31:42 浏览: 123
要在Python中绘制带有年份的x轴,可以使用matplotlib库。示例代码如下:
``` python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.array(['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019'])
y = np.array([5, 8, 6, 9, 12, 14, 16, 20, 23, 26])
# 绘制图形
fig, ax = plt.subplots()
ax.plot(x, y)
# 设置x轴标签
ax.set_xticks(x)
ax.set_xticklabels(x, rotation=45)
# 显示图形
plt.show()
```
在这个例子中,我们使用了一个包含年份的字符串数组作为x轴。使用`set_xticks`和`set_xticklabels`方法设置x轴标签,并使用`rotation`参数旋转标签,以便更好地显示。
相关问题
sns.barplot的x轴是年份,但是没有按年份排序
要按照年份排序,可以先将年份转换为 datetime 类型,并将其设置为 DataFrame 的索引。然后,使用 sort_index() 方法按照索引排序。最后再进行绘图即可。
下面是一个示例代码:
```python
import pandas as pd
import seaborn as sns
# 创建示例数据
data = {'year': [2018, 2020, 2019, 2017], 'value': [10, 30, 20, 15]}
df = pd.DataFrame(data)
# 将 year 转换为 datetime 类型并设置为索引
df['year'] = pd.to_datetime(df['year'], format='%Y')
df.set_index('year', inplace=True)
# 按照索引排序
df.sort_index(inplace=True)
# 绘制柱状图
sns.barplot(x=df.index.year, y='value', data=df)
```
这里的 x 轴使用了 `df.index.year`,它表示索引的年份部分。这样可以按照年份排序,并正确地显示在 x 轴上。
x轴为时间,y轴为数字,画图
当x轴为时间,y轴为数字时,您可以使用Bokeh库中的`DatetimeAxis`来处理时间轴。以下是一个示例,展示如何绘制x轴为时间的折线图:
```python
from bokeh.plotting import figure, show
from bokeh.models import DatetimeTickFormatter
from datetime import datetime
# 示例数据
x = [datetime(2022, 1, 1), datetime(2022, 2, 1), datetime(2022, 3, 1), datetime(2022, 4, 1)]
y = [4, 6, 2, 8]
# 创建一个绘图对象
fig = figure(x_axis_type="datetime")
# 绘制折线图
fig.line(x, y)
# 格式化x轴的时间显示
fig.xaxis.formatter = DatetimeTickFormatter(months=["%b %Y"])
# 显示图形
show(fig)
```
在这个例子中,我们使用`datetime`模块创建了一个时间序列列表`x`,并将其作为x轴数据传递给`line()`函数。通过将`x_axis_type="datetime"`传递给`figure()`函数,我们告诉Bokeh将x轴解释为时间轴。
为了格式化x轴的时间显示,我们使用`DatetimeTickFormatter`模块来指定显示的时间格式。在这个例子中,我们将月份和年份的格式设置为"%b %Y",即三个字母的月份缩写和四位数的年份。
最后,使用`show()`函数显示绘图。
您可以根据自己的需求修改和调整代码,例如设置y轴数据、添加标题、设置坐标轴标签等。