2

I am trying to plot matplotlib bar plot with one y-axis on the left and another y on the right with a common x-axis.The range column is on the x-axis. Perc column is on left y-axis and the count column is on the right y-axis. Please advise how to proceed.

Sample data is here - SampleFileHere

enter image description here

import numpy as np import pandas as pd import seaborn as sbn import matplotlib.pyplot as plt fig = plt.figure() ax = td['perc'].plot(kind="bar", alpha=0.7) plt.xticks(td['ranges'].tolist()) ax2 = ax.twinx() ax2.plot(ax.get_xticks(),td['count'],marker='o', c='navy', linewidth=4) 

I get the below error .

<ipython-input-24-c1d398c0d012> in <module>() 7 fig = plt.figure() 8 ax = td['perc'].plot(kind="bar", alpha=0.7) ----> 9 plt.xticks(td['ranges'].tolist()) 10 ax2 = ax.twinx() 11 ax2.plot(ax.get_xticks(),td['count'],marker='o', c='navy', linewidth=4) 
2
  • I am trying to provide a link to the excel. Please hold on . I am just searching how to do Commented Apr 22, 2017 at 0:08
  • Have provided the link to data Commented Apr 22, 2017 at 0:21

1 Answer 1

2

You cannot set the xticks to some non-numeric values. Instead you need to set the xticklabels to the entries from the "range" column.

import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt counts = np.array([56000,900,5000,6000,30000,3500,300]).astype(float) perc = counts/counts.sum() df = pd.DataFrame({"range": list("ABCDEFG"),"count":counts, "perc":perc}) fig = plt.figure() ax = df['perc'].plot(kind="bar", alpha=0.7) ax2 = ax.twinx() ax2.plot(ax.get_xticks(),df['count'],marker='o', c='navy', linewidth=4) ax.set_xticklabels(df['range']) ax.set_ylim(0,1.3*df["perc"].max()) ax2.set_ylim(0,1.3*df["count"].max()) ax2.grid(False) plt.show() 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.