Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple series with subplots for shared columns in DataFrames

I have two DataFrames with identical row indexes and column names that are sometimes only in one DataFrame, and sometimes in both. I wanted to plot data from columns that are in both DataFrames and arrange them in subplots. The final figure should look like this:

ColumnA1 + ColumnB1 ColumnA2 + ColumnB2
ColumnA3 + ColumnB3 ColumnA4 + ColumnB4

For now I tried to simply have the plots done, without arranging them in subplots. But if any of the columns is not present in both DataFrames, none of the plots are showing:

for column_name in [DataFrameA.columns, DataFrameB.columns]:
        DataFrameA[column_name].plot(label = "A")
        DataFrameB[column_name].plot(label = "B")
        plt.show()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Solution

Save the column names for each DataFrame as sets a and b. After that, create a new set c that contains only the elements which are contained in BOTH sets (the intersection of the sets). Next, use a for loop to iterate over each column name in c and plot the data. This is just like the code in the question, except iterating over the new set c instead of [DataFrameA.columns, DataFrameB.columns].

Code

a = set(list(DataFrameA))
b = set(list(DataFrameB))
c = a.intersection(b)

for column_name in c:
        DataFrameA[column_name].plot(label = "A")
        DataFrameB[column_name].plot(label = "B")
        plt.show()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading