1

I am plotting a bar chart of 'Time zone (UTC)' Vs 'Frequency', using value_counts() for column 'UTC_Hrs', in a pandas dataframe of twitter posts.

UTC_Hrs
-5.0
11.0
Nan
0.0

etc

I want the x axis to be ordered from, -11.0 to + 13.0, but I can't work out how to do it.

order = ["-11.0", "-10.0", "-9.0", "-8.0", "-7.0", "-6.0",  "-5.0", "-4.0",
         "-3.5", "-3.0", "0.0", "1.0" , "2.0","3.0", "4.0", "5.0",                
         "5.5","6.0","7.0", "8.0", "9.0", "10.0", "11.0", "13.0"]

I've found out how to order it as it occurs in the df by using, value_counts(sort=False):

df['UTC_Hrs'].value_counts(sort=False).plot(kind='bar')

I also found out how to pretend I had done it using ;-):

set_xticklabels(order) 

I've tried other multiple variations inspired by other answers and the pandas docs but nothing has worked. The most complex thing and maybe closest I got was to to use a dictionary and mapping but couldn't work out how to call this on value_counts, thinking this was the wrong approach.

UTC_Hrs = df['UTC_Hrs'] 
mapping = {UTC_Hrs: i for i, UTC_Hrs in enumerate(order)}
key = df['UTC_Hrs'].map(mapping)
dfx = df.iloc[key.argsort()]
dfx.plot(kind='bar')??? value_counts by referencing dict?

Any help and advice much appreciated, Thanks

1 Answer 1

1

You can use reindex with intersection order and s.index, but is necessary same types - both strings or both floats:

s = df['UTC_Hrs'].astype(str).value_counts()
s.reindex(np.intersect1d(order, s.index)).plot.bar()

s = df['UTC_Hrs'].value_counts()
s.reindex(np.intersect1d(np.array(order).astype(float), s.index)).plot.bar()
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for coming to the rescue for the second day in a row, much appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.