是否可以绘制名称相同颜色的列?

问题描述 投票:0回答:1

我正在尝试绘制一个包含许多具有相同名称的列的数据集。我试图重用我先前制作的绘图程序,但是问题是它以不同的颜色来绘制每列,而我希望具有same name的每一列都为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下载数据

python pandas matplotlib data-processing
1个回答
0
投票

好,出现问题是因为您有多个具有相同名称的列。因此,您需要进行处理。以下代码这样做:

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', "O.1":'r', "Mo": 'b', "Mo.1": 'b', 'Al':'g', "Al.1": '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])
   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()

将产生以下图像:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.