logo
down
shadow

Issues with the labels in image in matplotlib


Issues with the labels in image in matplotlib

By : Cheryl Macias
Date : November 18 2020, 11:13 AM
With these it helps By default, matplotlib automatically chooses tick locations at "even" intervals. Tick labels only occur at tick locations, so if you'd like to label every column and row, you'll need to set the tick positions as well as the tick labels.
Basically, you want something like:
code :
i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)
import numpy as np
import matplotlib.pyplot as plt

labels = ['D', 'F', 'A', 'G', 'DG', 'R', 'I', 'BS', 'COA', 'W', 'T']
data = np.random.random((len(labels), len(labels)))

fig, ax = plt.subplots()
im = ax.matshow(data, cmap='Pastel1')
fig.colorbar(im)

i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

ax.set(ylabel='True label', xlabel='Predicted label', title='Confusion Matrix')
plt.show()


Share : facebook icon twitter icon
Using an image for tick labels in matplotlib

Using an image for tick labels in matplotlib


By : Oleksiy Fiks
Date : March 29 2020, 07:55 AM
will be helpful for those in need Interesting question, and potentially has many possible solutions. Here is my approach, basically first calculate where the label '0' is, then draw a new axis there using absolute coordinates, and finally put the image there:
code :
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pylab as pl

A = np.random.random(size=(5,5))
fig, ax = plt.subplots(1, 1)

xl, yl, xh, yh=np.array(ax.get_position()).ravel()
w=xh-xl
h=yh-yl
xp=xl+w*0.1 #if replace '0' label, can also be calculated systematically using xlim()
size=0.05

img=mpimg.imread('microblog.png')
ax.matshow(A)
ax1=fig.add_axes([xp-size*0.5, yh, size, size])
ax1.axison = False
imgplot = ax1.imshow(img,transform=ax.transAxes)

plt.savefig('temp.png')
Rotating Matplotlib tick labels causes weird spacing issues

Rotating Matplotlib tick labels causes weird spacing issues


By : Allison Youngblood
Date : March 29 2020, 07:55 AM
To fix the issue you can do If xticklabels are of the same length, you won't have this kind of problem. But given different length of labels, you can encounter this kind of problem. Because the default rotation is from the center of the xlabel string. So you can try to set the rotation anchor properly from ['right', 'center', 'left'].
code :
ha = 'left' # or 'right'. Experiment with it.
ax.set_xticks(x) # set tick location
ax.set_xticklabels(xlabels, rotation=40, ha=ha) # rotate the labels with proper anchoring.
Replace Matplotlib legend's labels with image

Replace Matplotlib legend's labels with image


By : Bg777
Date : March 29 2020, 07:55 AM
To fix this issue The concept for creating an image in a legend is already presented in this question (Insert image in matplotlib legend) where an image is used as an artist for a legend entry.
In case you want a line handle and an image in the legend, the idea would be to create a handle that consists of both of them, positionned next to each other. The only problem is then to fine tune the parameters such that this looks appealing.
code :
import matplotlib.pyplot as plt
import matplotlib.lines
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.legend_handler import HandlerBase
from matplotlib.image import BboxImage

class HandlerLineImage(HandlerBase):

    def __init__(self, path, space=15, offset = 10 ):
        self.space=space
        self.offset=offset
        self.image_data = plt.imread(path)        
        super(HandlerLineImage, self).__init__()

    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):

        l = matplotlib.lines.Line2D([xdescent+self.offset,xdescent+(width-self.space)/3.+self.offset],
                                     [ydescent+height/2., ydescent+height/2.])
        l.update_from(orig_handle)
        l.set_clip_on(False)
        l.set_transform(trans)

        bb = Bbox.from_bounds(xdescent +(width+self.space)/3.+self.offset,
                              ydescent,
                              height*self.image_data.shape[1]/self.image_data.shape[0],
                              height)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)
        return [l,image]


plt.figure(figsize=(4.8,3.2))
line,  = plt.plot([1,2],[1.5,3], color="#1f66e0", lw=1.3)
line2,  = plt.plot([1,2],[1,2], color="#efe400", lw=1.3)
plt.ylabel("Flower power")

plt.legend([line, line2], ["", ""],
   handler_map={ line: HandlerLineImage("icon1.png"), line2: HandlerLineImage("icon2.png")}, 
   handlelength=2, labelspacing=0.0, fontsize=36, borderpad=0.15, loc=2, 
    handletextpad=0.2, borderaxespad=0.15)

plt.show()
Matplotlib.pyplot labels not displaying Hindi text in Labels,

Matplotlib.pyplot labels not displaying Hindi text in Labels,


By : P. Wo
Date : March 29 2020, 07:55 AM
may help you . Apparently matplotlib doesn't know how to render the characters. One way to solve this is to tell matplotlib which font to use. For example, say you will use "Nirmala". Put the font file at a proper location and you can code like this:
Note: I'm not sure how your tok.wordtokenize(text) works (similar to nltk's word_tokenize(s)?). So I changed that line to tokens = text.split(). Hope you won't mind.
code :
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

def dispersionPlot(text, words):
    tokens = text.split()
    print(words)
    x_length = len(tokens)
    y_length = len(words)
    x_list = []
    y_list = []
    for i in range(0 , x_length):
        for j in range(0 , y_length):
            if tokens[i] == words[j]:
                x_list.append(i+1)
                y_list.append(j)
    plt.plot(x_list, y_list, "b|", scalex=.1)
    hindi_font = FontProperties(fname = 'Nirmala.ttf')
    plt.yticks(list(range(len(words))), words, color="b", fontproperties=hindi_font)
    plt.ylim(-1, len(words))
    plt.xlabel("Lexical Distribution")
    plt.show()

text = "प्रदूषण आज के समय का सबसे बड़ा अभिशाप है जो हमारे विज्ञानं की देन है। प्रदूषण के बढ़ने से हमारे धरती पे बहुत सी समस्याएं पैदा हो गई जिसे अगर समय रहते न रोक गया तो वो दिन दूर नही जब धीरे-धीरे सब खतम हो जायेगा। प्रदुषण के तत्त्व मनुष्यों द्वारा उत्पन्न किया गया पदार्थ या वेस्ट मटेरियल होता है जो की प्राकृतिक संसाधन जैसे की वायु, जल और भूमि आदि को प्रदूषित करते है| प्रदूषण जहरीली गैस, कीटनाशक, शाकनाशी, कवकनाशी, ध्वनि, कार्बनिक मिश्रण, रेडियोधर्मी पदार्थ हो सकते है। दिन पर दिन वनो की कटाई, कारखानो का प्रदूषित धुआं, वाहनो का धुँआ हमारे पूरे वातावरण को दूषित करता जा रहा है। प्रदूषण कई तरह के होते है परन्तु इनमे से सबसे हानिकारक जल प्रदूषण, वायु प्रदूषण, और ध्वनि प्रदूषण है। नगरो का सारा कूड़ा करकट और मल जल में डाल दिया जाता है जिससे हमारे पीने का पानी अशुद्ध हो गया है और इसके सेवन से हमारे शरीर को अनेक तरह की बीमारियां लग रही है। वायु प्रदूषण हमारे द्वारा उत्पन की गई गसो से पूरी हवा में फ़ैल जाता है और वही दूषित हवा को हम श्वास के साथ अंदर लेते है और कई तरह की बिमारियों का शिकार बन जाते है। ध्वनि प्रदूषण का कारण बढ़ती जनसख्या है जिसके कारण शोरगुल बढ़ता जा रहा है जैसे की वाहनो का शोर, कारखानो में मशीनो का शोर इत्यादि । प्रदूषण पर नियंत्रण पाने के लिए संयुक्त प्रयास की आवश्यकता है जिससे की हम एक स्वस्थ्य और प्रदुषण मुक्त वातावरण पा सके।"
words = ["है", "प्रदूषण"]
dispersionPlot(text, words)
How to apply logarithmic axis labels without log scaling image (matplotlib imshow)

How to apply logarithmic axis labels without log scaling image (matplotlib imshow)


By : Sandeep
Date : March 29 2020, 07:55 AM
I hope this helps you . You need to use a custom formatter. Here's an example from the matplotlib docs: https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
I tend to use FuncFormatter as the example does. The main trick is that your function need to take to arguments x and pos. I honestly don't know what pos is for. Perhaps no even intentionally, but you can use FuncFormatter as a decorator, which is what I do below:
code :
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

@plt.FuncFormatter
def fake_log(x, pos):
    'The two args are the value and tick position'
    return r'$10^{%d}$' % (x)

x=10**np.random.random(10000)*5
y=10**np.random.random(10000)*5

samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x), bins=50)    

fig, (ax1) = plt.subplots()
ax1.imshow(samps, extent=[0, 5, 0, 5])
ax1.xaxis.set_major_formatter(fake_log)
ax1.yaxis.set_major_formatter(fake_log)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
Related Posts Related Posts :
  • Remove commas in a string, surrounded by a comma and double quotes / Python
  • How to chain Django querysets preserving individual order
  • Comparison with Python
  • How to find backlinks in a website with python
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org