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

IDLE中Matplotlib/Pandas颜色映射绘图无法显示问题排查

解决IDLE中Matplotlib/Pandas绘图不显示的问题

问题根源

Matplotlib在IDLE环境中默认不会自动渲染并弹出图像窗口,你的代码缺少触发图像显示的关键命令,这是导致只打印提示、看不到图像的核心原因。

解决方法

1. 核心修改:添加图像显示命令

在每个绘图函数的末尾添加plt.show(),强制Matplotlib弹出图像窗口。如果多个绘图连续执行,每个函数单独调用plt.show()可以避免图像重叠。

2. 修改后的完整代码

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

def fig1():
    # 导入数据创建DataFrame
    wine_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data' 
    wine_column_headers = ['Alcohol','Malic acid','Ash','Alcalinity of ash',  
                       'Magnesium','Total phenols','Flavanoids',
                       'Nonflavanoid phenols','Proanthocyanins','Color intensity', 
                       'Hue','OD280/OD315 of diluted wines' ,'Proline']
    wine_df = pd.read_csv(wine_url, names = wine_column_headers)

    # 创建画布
    fig, ax1 = plt.subplots()
    fig.set_size_inches(13, 10)

    # 设置标签
    ax1.set_xlabel('Alcohol')
    ax1.set_ylabel('Color Intensity')
    ax1.set_title('Relationship Between Color Intensity and Alcohol Content in Wines')

    # 颜色映射序列
    c = wine_df['Color intensity']

    # 绘制散点图
    plt.scatter( wine_df['Alcohol'], wine_df['Color intensity'] , c=c, 
            cmap = 'RdPu', s = wine_df['Proline']*.5, alpha =0.5)
    cbar = plt.colorbar()
    cbar.set_label('Color Intensity')
    
    print("fig1 complete")
    plt.show()  # 新增:触发图像显示

def fig2():
    x = np.arange(0, 100)
    y = x
    t = x
    df = pd.DataFrame([x,y]).T

    df.plot(kind="scatter", x=0, y=1, c=t, cmap="jet")

    print("fig2 complete")
    plt.show()  # 新增:触发图像显示

def fig3():
    df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
                    [6.4, 3.2, 1], [5.9, 3.0, 2]],
                   columns=['length', 'width', 'species'])
    # 若要学习颜色映射,建议改为传数值列+cmap,示例:
    # ax1 = df.plot.scatter(x='length', y='width', c='species', cmap='viridis')
    ax1 = df.plot.scatter(x='length', y='width', c='DarkBlue')
    print("fig3 complete")
    plt.show()  # 新增:触发图像显示

fig1()
fig2()
fig3()

3. 额外适配提示

  • 如果添加plt.show()后仍无图像,可在代码开头强制指定IDLE兼容的后端:
    plt.switch_backend('TkAgg')
    
  • fig3中当前c='DarkBlue'是设置固定点颜色,若要测试颜色映射功能,应传入数值型列(如c='species')并搭配cmap参数,才能看到颜色随数值变化的效果。

内容的提问来源于stack exchange,提问作者Henrique Eira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:10:28