You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook绘图X轴年份不显示问题(基辅迪纳摩数据)

解决Jupyter Notebook绘图X轴不显示年份的问题

问题场景

尝试基于维基百科数据绘制基辅迪纳摩队历年胜负比率图表,在Jupyter Notebook中绘图时X轴未显示年份。即使尝试将年份设置为DataFrame的索引,该问题仍未解决,原代码如下:

from ipywidgets import interact
import ipywidgets as widgets
import pandas as pd
import requests
import matplotlib.pyplot as plt
import numpy as np


url = "https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D1%81%D0%B5%D0%B7%D0%BE%D0%BD%D0%BE%D0%B2_%D0%A4%D0%9A_%C2%AB%D0%94%D0%B8%D0%BD%D0%B0%D0%BC%D0%BE%C2%BB_%D0%9A%D0%B8%D0%B5%D0%B2"


response = requests.get(url)


dfs = pd.read_html(response.text)

df = dfs[0]
mask = pd.to_numeric(df['В'], errors='coerce').notna() & (pd.to_numeric(df['П'], errors='coerce').notna())

df = df[mask]

new_names = {
    'Сезон': 'Year',
}

df = df.rename(columns=new_names)

df['Year'] = df['Year'].str.replace(r'\(.*\)', '', regex=True).str.replace(' ', '')
df['В'] = pd.to_numeric(df['В'], errors='coerce')
df['П'] = pd.to_numeric(df['П'], errors='coerce')
df['Year'] = pd.to_numeric(df['Year'], errors='coerce')
df['Ratio'] = df['В'] / (df['В']+df['П'])
df['TotalGames'] = df['В']+df['П']
df = df[['Year','Ratio', 'TotalGames']]
window_size = 5
degree = 4
coefficients = np.polyfit(df['Year'], df['Ratio'], degree)
df['PolynomialMovingAverage'] = np.polyval(coefficients, df['Year'])
df.set_index("Year")
potential_columns=[]
for col in df.columns:
    potential_columns.append(col)
potential_columns.pop(0)
@interact(col_names=widgets.SelectMultiple(
    options=potential_columns,
    value=(potential_columns[0],),
    description='Columns'))
def plot_data(col_names):
    plt.figure(figsize=[12,8])
    plt.gcf().suptitle(str(col_names))
    if len(col_names) ==2:
        plt.plot(df[list(col_names)[0]],'b')
        ax=plt.twinx()
        ax.plot(df[list(col_names)[1]],'r')
    else:
        plt.plot(df[list(col_names)])

问题原因

  1. df.set_index("Year")未重新赋值给df,DataFrame的索引并未实际修改,年份仍以普通列存在。
  2. 绘图时未指定X轴数据,matplotlib默认使用行号作为X轴刻度,因此不会显示年份。

修改后的代码

from ipywidgets import interact
import ipywidgets as widgets
import pandas as pd
import requests
import matplotlib.pyplot as plt
import numpy as np


url = "https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D1%81%D0%B5%D0%B7%D0%BE%D0%BD%D0%BE%D0%B2_%D0%A4%D0%9A_%C2%AB%D0%94%D0%B8%D0%BD%D0%B0%D0%BC%D0%BE%C2%BB_%D0%9A%D0%B8%D0%B5%D0%B2"


response = requests.get(url)


dfs = pd.read_html(response.text)

df = dfs[0]
mask = pd.to_numeric(df['В'], errors='coerce').notna() & (pd.to_numeric(df['П'], errors='coerce').notna())

df = df[mask]

new_names = {
    'Сезон': 'Year',
}

df = df.rename(columns=new_names)

df['Year'] = df['Year'].str.replace(r'\(.*\)', '', regex=True).str.replace(' ', '')
df['В'] = pd.to_numeric(df['В'], errors='coerce')
df['П'] = pd.to_numeric(df['П'], errors='coerce')
df['Year'] = pd.to_numeric(df['Year'], errors='coerce')
df['Ratio'] = df['В'] / (df['В']+df['П'])
df['TotalGames'] = df['В']+df['П']
df = df[['Year','Ratio', 'TotalGames']]
window_size = 5
degree = 4
coefficients = np.polyfit(df['Year'], df['Ratio'], degree)
df['PolynomialMovingAverage'] = np.polyval(coefficients, df['Year'])
# 关键修改1:将年份设置为索引并赋值给df
df = df.set_index("Year")
potential_columns=[]
for col in df.columns:
    potential_columns.append(col)
potential_columns.pop(0)
@interact(col_names=widgets.SelectMultiple(
    options=potential_columns,
    value=(potential_columns[0],),
    description='Columns'))
def plot_data(col_names):
    plt.figure(figsize=[12,8])
    plt.gcf().suptitle(str(col_names))
    if len(col_names) ==2:
        # 关键修改2:指定X轴为df的索引(年份)
        plt.plot(df.index, df[list(col_names)[0]],'b')
        plt.xlabel('年份')
        # 旋转X轴标签避免重叠
        plt.xticks(rotation=45)
        ax=plt.twinx()
        ax.plot(df.index, df[list(col_names)[1]],'r')
    else:
        plt.plot(df.index, df[list(col_names)])
        plt.xlabel('年份')
        plt.xticks(rotation=45)
    # 调整布局,防止标签被截断
    plt.tight_layout()

修改说明

  1. 索引生效:将df.set_index("Year")改为df = df.set_index("Year"),确保年份被设置为DataFrame的索引。
  2. 指定X轴数据:绘图时使用df.index作为X轴数据,明确关联年份与对应的数据点。
  3. 优化显示:添加X轴标签、旋转刻度标签并调整布局,避免年份标签重叠或被截断。

内容的提问来源于stack exchange,提问作者Anton Pazuslkyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:22:03