【发布时间】:2019-12-25 19:59:16
【问题描述】:
如果不调用 plt.legend(),则显示绘图。有了它,我得到:
<matplotlib.legend.Legend at 0x1189a404c50>
我在 JupyterLab、Python 3、Anaconda 工作 我不明白是什么阻止了图例的显示。如果没有最后一个 for 循环遍历 xarray,即如果我只加载一个频谱来绘制,则图例工作正常。有任何想法吗?谢谢! 代码如下:
import colour
from colour.plotting import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib
import scipy.integrate as integrate
from scipy import interpolate
### Read Spectrum file ###
xarray = []
yarray = []
while True:
# Separator in CSV
separator = input("Separator: [, or tab or semicolon]")
if separator in {',','comma'}:
separator = ','
elif separator in {'tab','TAB'}:
separator = '\t'
elif separator in {';','semicolon'}:
separator = ';'
else:
print("Separator must be one of the listed")
# Header in CSV
headerskip = input("Header [y/n]")
if headerskip in {'y','yes','Y','Yes','YES'}:
headerskip = 1
elif headerskip in {'n','no','N','No','NO'}:
headerskip = 0
else:
print("Header?")
# Choose CSV file
filename = input("Filename")
try:
spectrum = pd.read_csv(filename, sep = separator, header = None, skiprows = headerskip, index_col=0)
except FileNotFoundError:
print("Wrong file or file path")
# Convert to our dictionary
spec = spectrum[1].to_dict() #functional dictionary
sample_sd_data = {int(k):v for k,v in spec.items()} # changes index to integer
# Do color calculations
sd = colour.SpectralDistribution(sample_sd_data)
cmfs = colour.STANDARD_OBSERVERS_CMFS['CIE 1931 2 Degree Standard Observer']
illuminant = colour.ILLUMINANTS_SDS['D65']
XYZ = colour.sd_to_XYZ(sd, cmfs, illuminant) #tristimulus values.
print(XYZ)
xy = colour.XYZ_to_xy(XYZ) # chromaticity coordinates
x, y = xy
print(xy)
xarray.append(x)
yarray.append(y)
# Query to add another file
addfile = input("Add another spectrum [y,n]")
if addfile in {'y','yes','Y','Yes','YES'}:
print("adding another file")
elif addfile in {'n','no','N','No','NO'}:
print("done with adding files")
break
else:
print("Add another file? Breaking loop")
break
# Plotting the *CIE 1931 Chromaticity Diagram*.
# The argument *standalone=False* is passed so that the plot doesn't get
# displayed and can be used as a basis for other plots.
#plot_single_sd(sd)
print(xarray)
print(yarray)
plot_chromaticity_diagram_CIE1931(standalone=False)
# Plotting the *CIE xy* chromaticity coordinates.
for i in range(len(xarray)):
x = xarray[i]
y = yarray[i]
plt.plot(x, y, '-p', color='gray',
markersize=15, linewidth=4,
markerfacecolor='None',
markeredgecolor='gray',
markeredgewidth=2,
label=str(i))
plt.plot(.3,.3, '-o', label='test')
# Customizing plot
plt.grid(True, linestyle=':')
plt.axis('equal') # disable this to go x to zero, however it will hide 500nm label
plt.xlim(0,.8)
plt.ylim(0,.9)
#plt.legend(framealpha=1, frameon=True, handlelength=0) # set handlelength to 0 to destroy line over the symbol
【问题讨论】:
-
plt.show()显示了一个绘图。为此,您必须设置一个后端。如果这没有自动发生,您可以通过%matplotlib ...或matplotlib.use(...)或plt.switch_backend(...)进行设置。
标签: python python-3.x matplotlib legend