Question
I am trying to plot a vector using python and matplotlib. My problem is that in matplotlib.pyplot, the x-axis of my data starts with 0 and ends on 23. And in the graph the same is considered.
What I want is that this axis starts with label 1 (it is related to the first y value, or value #0 in natural python indexing) and ends on 24 (related to the last y value, or value #23 in natural python indexing). I tried matplotlib.pyplot.xlimwith xmin=1, but the problem is that, this way, the first dimension (0) disappears in the graph, and the upper bound continues to be 23. I want it to be 24 and the first y value having its x value labeled as 1 (not 0).
This solution is not working for me. I am trying to have the labels [1,24] in the x-axis of the graph instead of [0,23]. As I wrote, if I start with 1 in x axis using xlim=1 or set_xlim=1, the first y value (dimension 0 of the vector) is not shown in the graph. It starts with second y value (dimension 1 of the vector) and ends with the last value. I don't want it. Here is the source code I am using:
- import matplotlib.pyplot as pp
- import numpy as np
- a=np.array( [0.10478151, 0.09909564, 0.01319826, 0.00743225, 0.00483721, 0.18202419, 0.01732046, 0.04153536, 0.03317991, 0.0536289, 0.00585423, 0.00929871, 0.00629363, 0.12180654, 0.00607781, 0.03752038,0.05547452, 0.01459015, 0.00604909, 0.01132442, 0.00710363, 0.11159429, 0.0079922, 0.04198672])
- pp.xlabel('Dimension')
- pp.ylabel('Importance')
- ax=pp.subplot(111)
- ax.set_xlim(1, 24)
- dim=np.arange(1,24,1);
- ax.plot(a, 'ro', color='r',linewidth=1.0, label="Graph2")
- pp.xticks(dim)
- pp.grid()
- pp.show()
- pp.close()
It is expected that the first y value will be shown in x=1 and the last in x=24. But Python indexing starts with 0, so, looks like the code is 'shifting' the values, starting in x=2 (or x=1 in python natural indexing).
How-To
You can get the result you want by using numpy.roll:
to shift the values you want from your original array onto the indices 1 to 23, and then append the final element of your original array so it is at index 24. The code would be:
- import matplotlib.pyplot as pp
- import numpy as np
- a=np.array( [0.10478151, 0.09909564, 0.01319826, 0.00743225, 0.00483721, 0.18202419, 0.01732046, 0.04153536, 0.03317991, 0.0536289, 0.00585423, 0.00929871, 0.00629363, 0.12180654, 0.00607781, 0.03752038,0.05547452, 0.01459015, 0.00604909, 0.01132442, 0.00710363, 0.11159429, 0.0079922, 0.04198672])
- pp.xlabel('Dimension')
- pp.ylabel('Importance')
- ax=pp.subplot(111)
- ax.set_xlim(1, 24)
- dim=np.arange(1,25,1)
- ax.plot(np.append(np.roll(a,1),a[23]), 'ro', color='r',linewidth=1.0, label="Graph2")
- pp.xticks(dim)
- pp.grid()
- pp.show()
- pp.close()
Note the change in the line
- dim=np.arange(1,25,1)
沒有留言:
張貼留言