我有很長的桌子,這是一個例子:

我想要的是根據影像編號進行繪圖。以 1,2,3 形式給出,并在繪圖上散布 xy(在第 2 列和第 3 列中給出)坐標。顏色應根據型別,如綠色為P,紅色為F等。
另外,我希望它們單獨繪制而不是在圖表中,并將它們保存為 image.1 image2 和 image 3。
請提出一個可能的解決方案。
我做了分組,現在我被困在這里。
到現在為止我所做的如下:
for index, group in data.groupby(['image number']):
group.plot(x='x',y='y', label=index, kind='scatter')
請幫我根據 MP 列在圖中添加顏色。

uj5u.com熱心網友回復:
所以據我了解,你dataframe看起來像這樣:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([
{"number": 1, "x": 2391, "y": 1994, "MP": "PP"},
{"number": 1, "x": 530, "y": 2707, "MP": "PP"},
{"number": 1, "x": 467, "y": 3208, "MP": "PP"},
{"number": 2, "x": 952, "y": 656, "MP": "PE"},
{"number": 2, "x": 3678, "y": 1409, "MP": "PE"},
{"number": 3, "x": 2950, "y": 177, "MP": "PMMA"},
{"number": 3, "x": 1039, "y": 306, "MP": "f"},
{"number": 3, "x": 2726, "y": 1827, "MP": "PMMA"},
{"number": 3, "x": 3578, "y": 2129, "MP": "PMMA"},
{"number": 3, "x": 3708, "y": 3624, "MP": "f"},
# rest of dataframe entries...
])
如果您想使用 制作這些散點圖matplotlib,您可以迭代資料框并使用plt.scatter來繪制單個粒子,如下所示:
scheme = {
"PP": "m", # PP is magenta
"PE": "g", # PE is green
"PMMA": "c", # PMMA is cyan
"f": "r", # f is red
# put more colours here...
}
def plot_single(df, num, scheme):
for i in range(len(df.index)):
if df["number"][i] == num:
plt.scatter(x=df["x"][i], y=df["y"][i], c = scheme[df["MP"][i]] if df["MP"][i] in scheme else "k")
# V change these as needed V
plt.title("Particle " str(num))
plt.xlabel("x")
plt.ylabel("y")
# ^ change these as needed ^
plt.show()
例如,如果您嘗試plot_single(df, 1, scheme)使用 的小片段dataframe,您將得到以下圖表:

要進一步自定義散點圖,您可以添加圖例、更改配色方案、修改散點圖等。
編輯:
如果你想要一張圖上的所有散點圖,你可以用這樣的函式來做到這一點:
def plot_all(df, scheme):
for i in range(len(df.index)):
plt.scatter(x=df["x"][i], y=df["y"][i], c = scheme[df["MP"][i]] if df["MP"][i] in scheme else "k")
plt.title("All Particles")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
您可以通過plot_all(df, scheme)在 shell 中鍵入來呼叫它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420951.html
標籤:
