user12809368
user12809368

Reputation:

Plotting boolean column in separate charts for True/False

I am having some issues in plotting data, also with checking unique values in a column within a dataframe. Specifically, I would need to plot data where a condition is satisfied: if rows in a column have value True then I would like to plot them; if they have value False, then I would like to have another separate plot. The problem is that my code plots one empty plot, then a plot with values True or False. I do not know how to plot beside (in a different plot) rows having values False.

My data is:

Date               Sold
03/15/2020         True
03/15/2020         True
03/15/2020         True
03/15/2020         True
03/16/2020         False
03/16/2020         True
03/16/2020         False
03/17/2020         False
03/17/2020         True 
03/17/2020         True
03/17/2020         False
03/18/2020         True

To convert Date from object to datetime I did:

df['Date']= pd.to_datetime(df['Date'])

The code I want to fix is the following:

counts = df.loc[df['Sold']==True].groupby([df['Date']]).count()
plt.ylabel('Count', fontsize=10)
counts.plot(rot=45,legend=None)
plt.figure()

The output(s) (I do not know why I am getting the first one) for the line plots generated by the first code above are:

enter image description here

enter image description here

The expected output should be one line plot in case Date are different (e.g. from 03/16/2020 to 03/31/2020), one for True values and one for False value.

Upvotes: 0

Views: 3406

Answers (1)

111Seven
111Seven

Reputation: 71

The first empty plot is because of plt.ylabel(). As plt.ylabel() is defined before plot(), its creating an empty plot and putting the ylabel.

edited for better plotting:

counts = df["Date"].groupby(df["Sold"]).value_counts()

#creating lists for better x-ticks and y-ticks values
#x-ticks
date = df["Date"].tolist()
date = set(date)
date = list(date)
#yticks
nums =  counts.tolist()
nums =  [i for i in range(max(nums)+1)]

#plotting False
plt.figure()
counts[0].plot(rot=45)
plt.legend("False")
plt.ylabel('Count', fontsize=10)
plt.xticks(ticks = date, fontsize=10)
plt.yticks(ticks = nums, fontsize=10)


#plotting True
plt.figure()
counts[1].plot(rot=45)
plt.ylabel('Count', fontsize=10)
plt.legend("True")
plt.xticks(ticks = date, fontsize=10)
plt.yticks(ticks = nums, fontsize=10)

The plots from the code:

enter image description here enter image description here

Upvotes: 2

Related Questions