NNNNN
NNNNN

Reputation: 3

how to make several plots in one figure?

I made a matlab-function that plots a graph. I need to group the data given by 'type' and plot a graph of the number of transactions, which is named as 'amount' in the given data. This is what I have now below.

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data=pd.read_csv 
('https://raw.githubusercontent.com/soulJ90/RPythonClass/main/credit.txt', 
sep=" ")
grouped=data.groupby('type')
data[data.amount.isnull()]
na_indexs=data[data.amount.isnull()].index
fill_value=data.groupby("type").amount.median()
result = pd.DataFrame()
for name, group in data.groupby('type'):
     c = group.fillna(group.median())
result = pd.concat([result,c])
fig, ax= plt.subplots()
for name, group in result:
    ax.plot(group.date,group.amount,label=name)
plt.figure(figsize=(14,6))
ax.legend(loc='upper right',ncol=2, fontsize=11)
plt.xlabel("date")
plt.ylabel("the number of transactions")
plt.title("the number of credic card transactions", fontsize=15)
plt.show()

I need to make a figure as below. But currently it is not working. Could you please help me?enter image description here

Upvotes: 0

Views: 64

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Try:

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data=pd.read_csv('https://raw.githubusercontent.com/soulJ90/RPythonClass/main/credit.txt', sep=" ")
ax = data.groupby(['date', 'type'])['amount'].count().unstack().plot(figsize=(12,8))
ax.legend(loc='upper right')
ax.set_ylabel('Number of Transactions')

Output:

enter image description here

Details:

Use groupby to create both the x axis and y axis, then unstack that multiindex to create columns in your dataframe representing the series ('type'). Use pandas.DataFrame.plot to create graphy with multiple lines (series) based on columns in the dataframe.

Upvotes: 1

Related Questions