Python 中按列值對散點圖進行顏色編碼
在資料視覺化中,為不同類別分配顏色可以增強清晰度並揭示模式。此功能在 R 的 ggplot2 中很容易使用,但是我們如何使用 pandas 和 matplotlib 在 Python 中實現相同的功能?
更新:Seaborn 增強
自原始答案以來,Seaborn 已成為一個強大的庫,用於創建信息豐富且具有視覺吸引力的情節。它最近的更新提供了基於列值對散佈圖進行著色的便捷函數:
- 使用seaborn.relplot:這個高階函數結合了matplotlib.pyplot.scatter 和Seaborn 的各個面向FacetGrid。它根據指定的色調和順序參數自動處理顏色編碼。
- 將 matplotlib.pyplot.scatter 對應到 seaborn.FacetGrid:與原始方法類似,您可以將 scatter 函數對應到FacetGrid 並根據色調自訂顏色。
原始Pandas 和Matplotlib 方法
對於那些尋求直接使用Matplotlib 方法的人,這裡有一個分配顏色的自訂函數基於分類列的點:
<code class="python">import matplotlib.pyplot as plt import pandas as pd def dfScatter(df, xcol='Height', ycol='Weight', catcol='Gender'): fig, ax = plt.subplots() categories = np.unique(df[catcol]) colors = np.linspace(0, 1, len(categories)) colordict = dict(zip(categories, colors)) df["Color"] = df[catcol].apply(lambda x: colordict[x]) ax.scatter(df[xcol], df[ycol], c=df["Color"]) return fig</code>
此函數根據唯一類別值建立顏色字典,並將對應的顏色指派給資料點。然後使用顏色編碼點產生散點圖。
示例
使用提供的示例數據框:
<code class="python">df = pd.DataFrame({'Height': np.append(np.random.normal(6, 0.25, size=5), np.random.normal(5.4, 0.25, size=5)), 'Weight': np.append(np.random.normal(180, 20, size=5), np.random.normal(140, 20, size=5)), 'Gender': ["Male", "Male", "Male", "Male", "Male", "Female", "Female", "Female", "Female", "Female"]})</code>
調用dfScatter 函數使用數據框:
<code class="python">fig = dfScatter(df) fig.savefig('color_coded_scatterplot.png')</code>
產生一個散點圖,其中點按性別著色:
[按性別著色的散點圖圖像]
Seaborn 的高級功能和自定義dfScatter 函數提供了靈活的選項,用於在Python 中向散佈圖添加顏色編碼,使資料視覺化更具資訊性和視覺吸引力。
以上是如何在 Python 中按列值對散佈圖進行顏色編碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

記事本++7.3.1
好用且免費的程式碼編輯器

禪工作室 13.0.1
強大的PHP整合開發環境