python - 使用数据框列更改 x 轴

标签 python pandas matplotlib plot

我有一个数据框,df 我曾经像这样生成两个系列的图:

year = [2002, 2002, 2002, 2002]
month = ['Jan', 'Feb', 'Mar', 'Apr']
column1 = [3.3, 3.0, 3.1, 3.2, 2.9]
column2 = [7.0, 7.1, 7.3, 6.9, 7.3]
Dataset = list(zip(year, month, column1, column2))
df = DataFrame(data = Dataset, columns = ['year', 'month', 'column1', 'column2'])
df['column1'].plot(legend = True, label = 'column1')
df['column2'].plot(legend = True, label = 'column2', title = \
"Figure 1", style = '--', linewidth = 2.5)

产生以下内容:

enter image description here

我的数据框中还有一列 df['year'],其中包含我希望沿 x 轴移动的值。我尝试了以下

plt.xticks(df['year'])

但发生了以下情况:

enter image description here

有没有一种方法可以使用 df['year'] 列并将其值作为 x 轴刻度线,而无需手动列出它们?我希望最终版本看起来像第一个图,但沿 x 轴具有 df['year'] 的唯一值。

最佳答案

要将刻度标签设置为某些数据框列的值,您需要将刻度位置设置为数据框的索引,并将标签设置为所述列中的值。

plt.xticks(df.index,df["year"].values)

完整示例:

from pandas import DataFrame
import matplotlib.pyplot as plt

year = [2002, 2002, 2002, 2002]
month = ['Jan', 'Feb', 'Mar', 'Apr']
column1 = [3.3, 3.0, 3.1, 3.2, 2.9]
column2 = [7.0, 7.1, 7.3, 6.9, 7.3]
Dataset = list(zip(year, month, column1, column2))
df = DataFrame(data = Dataset, columns = ['year', 'month', 'column1', 'column2'])
df['column1'].plot(legend = True, label = 'column1')
df['column2'].plot(legend = True, label = 'column2', title = \
      "Figure 1", style = '--', linewidth = 2.5)

plt.xticks(df.index,df["year"].values)

plt.show()

这当然会将所有标签显示为 2002 年,因为年份列中的所有值都是 2002 年。(但不确定这是否有意义。)

enter image description here

如果你只想标记每年的第一次出现,你可以像下面这样使用独特的年份

unique_years, ind = np.unique(df["year"].values,return_index=True)
plt.xticks(df.index[ind], unique_years)

结果是这样的:

enter image description here

关于python - 使用数据框列更改 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633654/

相关文章:

python - 如何查找Python数据框中单元格中第一次出现匹配的行索引(包含日期)

python - Django 为每个模型字段设置隐私选项

python - Django 中的自定义 WSGIRequestHandler.log_message?

python - 在 Pandas groupby 上使用 value_counts 时如何忽略空系列?

python - pandas read_excel函数用空格替换 "NA"?

python - Matplotlib 通过颜色或形状区分均值和中值

python - 如何在 Seaborn 或 Matplotplib 中制作组颜色条 xticks yticks

python - 如何在 seaborn fiddle 情节中为每个组分配不同的位置

python - 如何为 2D 直方图选择自定义 bin 大小?

python - Python 2.5 上选择模块的问题