1

I have gone through bunch of questions on SO on similar content and read to understand anatomy of it still I am unable to figure out solution how to rotate the label.Other sources referred Link1 Link2 Link3 Below is my effort

fig, ax = plt.subplots()

# Although I have commented out this part it would be great to know what is wrong with it
#xaxis = myfiledic.keys()
#yaxis = myfiledic.values()
#ax.plot(xaxis, yaxis)

plt.bar(range(len(myfiledic)), myfiledic.values())
plt.xticks(range(len(myfiledic)), myfiledic.keys())

for line in ax.xaxis.get_majorticklabels():
    print line
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)

plt.show()

The print line points to below output. I m just trying to plot some files with C code and number of lines in it. So xlabel is the name of file which I was expecting and below is what I am getting

Text(0,0,'add_2_arrays.c')
Text(0,0,'bst.c')
Text(0,0,'sort_string_array.c')
Text(0,0,'palindrome_int.c')
Community
  • 1
  • 1
oneday
  • 629
  • 1
  • 9
  • 32

1 Answers1

0

I'm not sure I understand what your question is. When I run your code, I get a bar plot with nicely rotated labels, just like you asked for.

Here's the code with some edits, to that it's a minimum working example:

Notice that I added align='center' to the plt.bar command, to get the bars centered on the tick mark rather than left-aligned on it.

import matplotlib.pyplot as plt
myfiledic = {
    'add_2_arrays.c': 1000,
    'bst.c': 1024,
    'sort_string_array.c': 42,
    'palindrome_int.c': 666,
}

fig, ax = plt.subplots()

plt.bar(range(len(myfiledic)), myfiledic.values(), align='center')
plt.xticks(range(len(myfiledic)), myfiledic.keys())

for line in ax.xaxis.get_majorticklabels():
    print line
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
# Make more room for the labels
plt.subplots_adjust(bottom=0.25)

plt.show()

resulting figure

Be aware that the order you get data from a dict in is arbitrary, so if you need to get the numbers in a specific order it's better to use an OrderedDict: from collections import OrderedDict and then put data into it in the order you want to read it back out.

As for this bit:

# Although I have commented out this part it would be great to know what is wrong with it
#xaxis = myfiledic.keys()
#yaxis = myfiledic.values()
#ax.plot(xaxis, yaxis)

What's wrong is that xaxis is a list of strings:

In [44]: xaxis
Out[44]: ['sort_string_array.c', 'sort_string_array.cS', 'bst.c', 'add_2_arrays.c']

In [45]: yaxis
Out[45]: [42, 666, 1024, 1000]

The plot(x,y) function puts dots in the axes according to numbers in x and y. The string 'sort_string_array.c' isn't a number, so it makes no sense to use it in a plot() command.

Åsmund
  • 1,332
  • 1
  • 15
  • 26