【问题标题】:Python - legend values duplicatePython - 图例值重复
【发布时间】:2016-09-27 01:35:33
【问题描述】:

我正在绘制一个矩阵,如下所示,图例一遍又一遍地重复。我试过使用 numpoints = 1 ,这似乎没有任何效果。有什么提示吗?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (10, 8) # set default figure size, 8in by 6inimport numpy as np

data = pd.read_csv('data/assg-03-data.csv', names=['exam1', 'exam2', 'admitted'])

x = data[['exam1', 'exam2']].as_matrix()
y = data.admitted.as_matrix()

# plot the visualization of the exam scores here
no_admit = np.where(y == 0)
admit = np.where(y == 1)
from pylab import *
# plot the example figure
plt.figure()
# plot the points in our two categories, y=0 and y=1, using markers to indicated
# the category or output
plt.plot(x[no_admit,0], x[no_admit,1],'yo', label = 'Not admitted', markersize=8, markeredgewidth=1) 
plt.plot(x[admit,0], x[admit,1], 'r^', label = 'Admitted', markersize=8, markeredgewidth=1) 
# add some labels and titles
plt.xlabel('$Exam 1 score$')
plt.ylabel('$Exam 2 score$')
plt.title('Admit/No Admit as a function of Exam Scores')
plt.legend()

【问题讨论】:

  • 这并不奇怪,因为您每次都在绘制多个数据集(线);它们恰好是相同的颜色和符号。
  • 您可能可以为每种类型绘制一个数据集,为这些数据集分配一个标签,然后为每种类型绘制剩余的数据集而没有标签。当admitno_admit 为空或仅对第一个数据集有效时,这可能会出现问题。

标签: python matplotlib legend


【解决方案1】:

如果你不举一个数据格式的例子,尤其是不熟悉 pandas 的人,你几乎不可能理解这个问题。 但是,假设您的输入具有以下格式:

x=pd.DataFrame(np.array([np.arange(10),np.arange(10)**2]).T,columns=['exam1','exam2']).as_matrix()
y=pd.DataFrame(np.arange(10)%2).as_matrix()

>>x
array([[ 0,  0],
   [ 1,  1],
   [ 2,  4],
   [ 3,  9],
   [ 4, 16],
   [ 5, 25],
   [ 6, 36],
   [ 7, 49],
   [ 8, 64],
   [ 9, 81]])

>> y
array([[0],
   [1],
   [0],
   [1],
   [0],
   [1],
   [0],
   [1],
   [0],
   [1]])

原因是从 DataFrame 到矩阵的奇怪转换,我想如果你有向量(一维数组)就不会发生这种情况。 对于我的示例,这是可行的(不确定它是否是最干净的形式,我不知道 xy 的二维矩阵来自哪里):

plt.plot(x[no_admit,0][0], x[no_admit,1][0],'yo', label = 'Not admitted', markersize=8, markeredgewidth=1) 
plt.plot(x[admit,0][0], x[admit,1][0], 'r^', label = 'Admitted', markersize=8, markeredgewidth=1) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2017-09-02
    • 2018-07-10
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多