Python / pycharm / matplotlib 训练结果曲线 的颜色、标记、线条等参数调整

本文展示了如何使用Matplotlib进行数据可视化,并通过示例介绍了不同类型的线条样式、标记符及颜色设置。此外,还利用Scikit-Learn进行了机器学习模型训练,并通过ROC曲线评估了多种模型的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:

http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib

http://stackoverflow.com/questions/8409095/matplotlib-set-markers-for-individual-points-on-a-line

示例1:

plt.subplots(1, 1)
x= range(100)
y= [i**2 for i in x]

plt.plot(x, y, linewidth = '1', label = "test", color=' coral ', linestyle=':', marker='|')
plt.legend(loc='upper left')
plt.show()

线形(linestyle)选择:

'-'       solid line style
'--'      dashed line style
'-.'      dash-dot line style
':'       dotted line style

marker选择:

'.'       point marker
','       pixel marker
'o'       circle marker
'v'       triangle_down marker
'^'       triangle_up marker
'<'       triangle_left marker
'>'       triangle_right marker
'1'       tri_down marker
'2'       tri_up marker
'3'       tri_left marker
'4'       tri_right marker
's'       square marker
'p'       pentagon marker
'*'       star marker
'h'       hexagon1 marker
'H'       hexagon2 marker
'+'       plus marker
'x'       x marker
'D'       diamond marker
'd'       thin_diamond marker
'|'       vline marker
'_'       hline marker

可用颜色选择:

参考:https://blog.youkuaiyun.com/alanguoo/article/details/79183021

 

示例2

import numpy as np
np.random.seed(10)

import matplotlib.pyplot as plt

from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,
                              GradientBoostingClassifier)
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve
from sklearn.pipeline import make_pipeline

n_estimator = 10
X, y = make_classification(n_samples=80000)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)

# It is important to train the ensemble of trees on a different subset
# of the training data than the linear regression model to avoid
# overfitting, in particular if the total number of leaves is
# similar to the number of training samples
X_train, X_train_lr, y_train, y_train_lr = train_test_split(
    X_train, y_train, test_size=0.5)

# Unsupervised transformation based on totally random trees
rt = RandomTreesEmbedding(max_depth=3, n_estimators=n_estimator,
                          random_state=0)

rt_lm = LogisticRegression(solver='lbfgs', max_iter=1000)
pipeline = make_pipeline(rt, rt_lm)
pipeline.fit(X_train, y_train)
y_pred_rt = pipeline.predict_proba(X_test)[:, 1]
fpr_rt_lm, tpr_rt_lm, _ = roc_curve(y_test, y_pred_rt)

# Supervised transformation based on random forests
rf = RandomForestClassifier(max_depth=3, n_estimators=n_estimator)
rf_enc = OneHotEncoder(categories='auto')
rf_lm = LogisticRegression(solver='lbfgs', max_iter=1000)
rf.fit(X_train, y_train)
rf_enc.fit(rf.apply(X_train))
rf_lm.fit(rf_enc.transform(rf.apply(X_train_lr)), y_train_lr)

y_pred_rf_lm = rf_lm.predict_proba(rf_enc.transform(rf.apply(X_test)))[:, 1]
fpr_rf_lm, tpr_rf_lm, _ = roc_curve(y_test, y_pred_rf_lm)

# Supervised transformation based on gradient boosted trees
grd = GradientBoostingClassifier(n_estimators=n_estimator)
grd_enc = OneHotEncoder(categories='auto')
grd_lm = LogisticRegression(solver='lbfgs', max_iter=1000)
grd.fit(X_train, y_train)
grd_enc.fit(grd.apply(X_train)[:, :, 0])
grd_lm.fit(grd_enc.transform(grd.apply(X_train_lr)[:, :, 0]), y_train_lr)

y_pred_grd_lm = grd_lm.predict_proba(
    grd_enc.transform(grd.apply(X_test)[:, :, 0]))[:, 1]
fpr_grd_lm, tpr_grd_lm, _ = roc_curve(y_test, y_pred_grd_lm)

# The gradient boosted model by itself
y_pred_grd = grd.predict_proba(X_test)[:, 1]
fpr_grd, tpr_grd, _ = roc_curve(y_test, y_pred_grd)

# The random forest model by itself
y_pred_rf = rf.predict_proba(X_test)[:, 1]
fpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)

plt.figure(1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_rt_lm, tpr_rt_lm, label='RT + LR')
plt.plot(fpr_rf, tpr_rf, label='RF')
plt.plot(fpr_rf_lm, tpr_rf_lm, label='RF + LR')
plt.plot(fpr_grd, tpr_grd, label='GBT')
plt.plot(fpr_grd_lm, tpr_grd_lm, label='GBT + LR')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve')
plt.legend(loc='best')
plt.show()

plt.figure(2)
plt.xlim(0, 0.2)
plt.ylim(0.8, 1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_rt_lm, tpr_rt_lm, label='RT + LR')
plt.plot(fpr_rf, tpr_rf, label='RF')
plt.plot(fpr_rf_lm, tpr_rf_lm, label='RF + LR')
plt.plot(fpr_grd, tpr_grd, label='GBT')
plt.plot(fpr_grd_lm, tpr_grd_lm, label='GBT + LR')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve (zoomed in at top left)')
plt.legend(loc='best')
plt.show()

参考:https://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#sphx-glr-auto-examples-ensemble-plot-feature-transformation-py

参考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html

<think>好的,我现在要解决PyCharmmatplotlibplt.show()无法显示图像的问题。首先,我需要回顾用户提供的引用内容。引用[1]提到用户通过conda卸载并重新安装matplotlib后出现了错误,引用[2]则给出了测试环境的代码示例,其中涉及导入numpy和matplotlib,并绘制简单的正弦曲线。用户的问题是在PyCharm中运行这段测试代码时,图像无法显示。 首先,我应该考虑可能的原因。常见的问题可能包括后端配置错误、依赖项缺失、或者IDE设置问题。Matplotlib的后端决定了如何渲染图形,如果后端设置不正确,可能导致图像无法显示。例如,某些后端需要GUI支持,而PyCharm默认可能使用非交互式后端。 接下来,我需要检查用户的环境配置是否正确。用户使用的是Anaconda环境,在PyCharm中可能需要正确配置项目的解释器路径,确保指向正确的conda环境。如果解释器路径错误,可能导致库导入失败或版本冲突。 然后,测试代码是否完整。用户的测试代码包含了生成数据、绘图和plt.show(),这一步是正确的,但需要确认是否有其他代码干扰,比如是否在脚本末尾添加了必要的show()调用。如果没有调用show(),图像也不会显示。 另一个可能的原因是matplotlib的后端设置。有些情况下,特别是在非交互式环境中,matplotlib可能默认使用agg这样的非交互式后端,这样plt.show()不会弹出窗口。可以尝试在代码中显式设置后端,例如使用TkAgg、Qt5Agg等。例如,在导入matplotlib之前添加: import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt 不过,这种方法可能因系统而异,有时需要安装相应的图形工具包,比如tk-dev包。 此外,检查PyCharm的设置是否正确。PyCharm有一个选项叫做“Show plots in toolwindow”,如果启用,图像会在IDE内部的工具窗口显示,而不是弹出独立窗口。用户可能需要禁用这个选项。路径是:File -> Settings -> Tools -> Python Scientific -> 取消勾选“Show plots in toolwindow”。 还需要检查是否有其他冲突的库或依赖项。例如,某些情况下,PyQt或PySide的版本不兼容可能导致后端问题。可以尝试更新或重新安装这些依赖。 另外,确保matplotlib和相关库(如numpy)都是最新版本,可以通过conda update matplotlib numpy来更新。有时候,旧版本存在已知的bug,更新可能解决问题。 如果上述方法无效,可能需要检查系统图形驱动或GUI库是否安装正确。例如,在Linux系统中,缺少tkinter可能导致TkAgg后端无法使用,可以通过系统包管理器安装tk-dev。 最后,查看错误信息是关键。用户提到在引用[1]中重新安装matplotlib后出现错误,但未具体说明错误内容。建议用户运行测试代码时查看控制台输出的错误信息,根据具体错误进行排查。例如,如果提示无法连接到显示,可能需要配置X服务器(在Linux下)或检查系统权限。 总结可能步骤: 1. 检查PyCharm的解释器配置是否正确指向conda环境。 2. 禁用PyCharm的科学模式中的绘图工具窗口。 3. 显式设置matplotlib的后端。 4. 确保所有依赖库已正确安装并更新。 5. 查看错误信息以进一步诊断。</think>针对PyCharmmatplotlib的$plt.show()$无法显示图像的问题,请按以下步骤排查: ### 一、检查后端配置 1. **强制指定图形后端** 在代码开头显式设置交互式后端(如TkAgg、Qt5Agg): ```python import matplotlib matplotlib.use('TkAgg') # 或 'Qt5Agg' import matplotlib.pyplot as plt ``` - 需确保系统已安装对应依赖(如`tk-dev`)[^1] - 若报错`ImportError`,通过`conda install tk`安装依赖 2. **禁用PyCharm科学模式** - 路径:`File -> Settings -> Tools -> Python Scientific` - 取消勾选**Show plots in toolwindow** (科学模式会拦截图像显示到独立窗口) ### 二、验证环境完整性 1. **更新库版本** 在Anaconda Prompt执行: ```bash conda update matplotlib numpy ``` 2. **重新安装matplotlib** ```bash conda remove matplotlib conda install matplotlib ``` ### 三、测试最小化代码 运行以下代码验证基础功能: ```python import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 1]) plt.show() # 确保调用show() ``` ### 四、排查系统级问题(Linux/Mac) 1. **安装图形界面库** - Ubuntu/Debian: `sudo apt-get install python3-tk` - Mac: 通过Homebrew安装`tk`: `brew install python-tk` 2. **检查显示权限** 若报错`Could not connect to display`,尝试: ```bash export DISPLAY=:0 # Linux远程连接时可能需要 ``` ### 五、PyCharm配置验证 1. **确认解释器路径** - `File -> Settings -> Project -> Python Interpreter` - 确保选择Anaconda环境中的Python(如`~/anaconda3/envs/<env_name>/bin/python`) 2. **重启PyCharm** 修改配置后重启IDE使设置生效[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值