Sayyiduna Abu Marthad al-Ghanawi (may Allah be pleased with him) said: I heard the Messenger of Allah (peace and blessings be upon him) say: "Do not sit on graves, and do not pray facing them."
The wording of these two hadiths is the same, except for the narration of Ibn Mazyad, which is reported from Wathilah bin al-Asqa' (may Allah be pleased with him).
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الجنائز / 7215
Bashir bin Nahik reports: Bashir (may Allah be pleased with him), the Companion of the Messenger of Allah (peace and blessings be upon him), whose name in the Jahiliyyah was Zahm bin Ma'bad, narrated to me that he (peace and blessings be upon him) asked him: "What is your name?" He said: Zahm bin Ma'bad. He (peace and blessings be upon him) said: "No, rather you are Bashir." So that became his name. He said: Once I was walking with the Messenger of Allah (peace and blessings be upon him), and he (peace and blessings be upon him) said: "O Ibn al-Khasasiyah! Have you woken up complaining against Allah, while you are walking with the Messenger of Allah (peace and blessings be upon him)?" I said: I have no complaint against Allah Almighty; my Allah has done me nothing but good. Then he (peace and blessings be upon him) came to the graves of the polytheists and said: "These are people whom much good has passed by." He (peace and blessings be upon him) repeated this three times. Then he (peace and blessings be upon him) came to the graves of the Muslims and said: "These have attained a great deal of good." He (peace and blessings be upon him) said this three times. He (peace and blessings be upon him) kept walking in this way when his glance fell on a man walking among the graves wearing sandals, so he (peace and blessings be upon him) said: "O wearer of the sandals! Woe to you, take off your sandals." When the man looked and saw that it was the Messenger of Allah (peace and blessings be upon him), he took off his sandals and threw them away.
A group narrated this hadith from al-Aswad bin Shayban, and it is known only through this chain.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الجنائز / 7216
Sayyiduna Anas bin Malik (may Allah be pleased with him) said that the Prophet of Allah (peace and blessings be upon him) said: "When a servant is placed in his grave and his companions turn back, he hears the sound of their sandals. Two angels come to him and say: 'What do you say about this man?' meaning Muhammad (peace and blessings be upon him)." He said: "If he is a believer, he says: 'I bear witness that he is the slave of Allah and His Messenger.' Then it is said to him: 'Look at your place in the Fire; Allah has exchanged it for you with a place in Paradise.' And he sees them both."
There is also the possibility that he (peace and blessings be upon him) saw filth on the sandals and for that reason ordered that they be taken off, and other possibilities exist as well.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الجنائز / 7217