有没有办法绘制具有相同名称和相同颜色的列?

Is there a way to plot columns with the same name as the same colour?

我正在尝试绘制一个包含许多同名列的数据集。我试图重用我之前制作的绘图程序,但问题是它以不同的颜色绘制每一列,相反我希望每一列的 名称相同 相同颜色。此外,它将每一列添加到图例中,导致我所附的图中出现很多混乱。有没有办法只为每种颜色贴一个标签?如果能帮助解决这些问题,我们将不胜感激!

Here is an example plot 如您所见,它没有将 "O" 都绘制为一种颜色,而是将其绘制为两种颜色,因为有两列数据,并在图例中创建了一个副本。

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

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name)
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()
   axes.yaxis.set_major_locator(MaxNLocator(integer=True))
   axes.set_xlim([xmin,xmax])
   axes.set_ylim(ymin,ymax)
   plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
   plt.ylabel('Intensity (counts/nC)', fontsize=12) 
   plt.legend(loc='upper center', fontsize=10) # Defines legend formatting
   plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()

您可以从这里下载数据link

好的,问题出现了,因为你有多个同名的列。所以,你需要处理它。以下代码这样做:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards


# this is the color dictionary
colors = {"O": 'r', "Mo": 'b', 'Al':'g'}

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name, color=colors[col_name.split('.')[0]])
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()

axes.yaxis.set_major_locator(MaxNLocator(integer=True))
axes.set_xlim([xmin,xmax])
axes.set_ylim(ymin,ymax)
plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
plt.ylabel('Intensity (counts/nC)', fontsize=12) 

# Defines legend formatting
custom_lines = [Line2D([0], [0], color='r', lw=4),
                Line2D([0], [0], color='b', lw=4),
                Line2D([0], [0], color='g', lw=4)]
plt.legend(custom_lines, ['O', 'Mo', 'Al'], loc='upper center', fontsize=10)

plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()

生成以下图像: